Recent Changes - Search:

Oktatás

* Programozás 2
  + feladatsor
  + C feladatsor
  + Python feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

* Adator. prog.
  + feladatsor
  + quick link

Teaching

* Prog. for Data Sci.
  ◇ exercises
  ◇ quick link

teaching assets


Félévek

* 2025/26/1
* archívum


Linkek

* kalendárium
   - munkaszüneti napok '20
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C++
* C#
* Clojure
* D lang.
* Java
* Nim
* Scala


[ edit | logout ]
[ sandbox | passwd ]

mutable slice -> immutable slice

Let's see how to convert a mutable slice to an immutable slice.

With copy

(1) copy
import std.stdio;
import std.conv;

void main()
{
    int[] slice = [1, 2, 3];
    auto immSlice = to!(immutable int[])(slice);

    slice[0] = 10;

    writeln(slice); // [10, 2, 3]
    writeln(immSlice); // [1, 2, 3]
}

Notes:

  • Here, we make a copy of slice. The result, immSlice will be an immutable copy of the original slice.
  • Notice the syntax. In "to!(immutable int[])(slice)", (slice) at the end must be between parentheses.

With transformation

(2) transformation
import std.stdio;
import std.exception; // assumeUnique()

void main()
{
    int[] slice = [1, 2, 3];

    auto immSlice = assumeUnique(slice);

    writeln(slice is null); // true
    writeln(immSlice); // [1, 2, 3]

    // immSlice[0] = 10; // error
}

Notes:

  • Here, no copy operation happens. immSlice will be an immutable view on the original slice.
  • assumeUnique(slice) sets the reference slice to null. Thus, after the transformation, the slice cannot be changed via the reference slice. This is done to avoid this kind of error.
  • After the transformation, immSlice is an immutable slice.
Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2025 September 19, 11:42