Value Type
A value type is a type whose terms are passed by copying. For a variable of value type, the data itself instead of the reference to the data is stored. Due to being passed by copying, value types have simpler semantics with respect to mutation than reference types, making the program more predictable and reliable.
Taking the most common concurrency security problem as an example: When a reference-type object is transferred to a different thread of a program, accessing a field of the object will cause an unpredictable data race. If instead the object has value semantics, it can be ensured that the object is completely copied during transfer, so that each thread accesses the value independently, thereby ensuring concurrency safety.
Cangjie supports value types. In addition to common numeric types, Cangjie also supports implementing user-defined value types via structs.
In the following example, Point
is a value type. Therefore, after values are assigned, a
and b
are independent of each other. The modification of a
does not affect b
.
struct Point {
var x: Int
var y: Int
init(x: Int, y: Int) { ... }
...
}
var a = Point(0, 0)
var b = a
a.x = 1
print(b.x) // 0