Middle
What are the differences between value type and reference type in programming languages?
sobes.tech AI
Answer from AI
Value types (for example, struct, enum, primitive numeric types) store their value directly. When assigned or passed to a function, a copy of the value is created.
Reference types (for example, class, function, closure) store a reference to the memory location where the actual value resides. When assigned or passed, a copy of the reference is created, pointing to the same value in memory.
Main differences:
| Characteristic | Value Type | Reference Type |
|---|---|---|
| Storage method | The value is stored directly in the variable | The variable stores a reference to the value |
| Assignment | Copies the value | Copies the reference (points to the same object) |
| Modification | Changing the copy does not affect the original | Changes via the reference affect the original |
| Memory location | Usually stack (for local variables) | Usually heap |
| Memory management | Automatic (when leaving scope) | ARC (Automatic Reference Counting) |
Example in Swift:
// value type
struct PointStruct {
var x: Int
var y: Int
}
var point1 = PointStruct(x: 1, y: 2)
var point2 = point1 // copies the value
point2.x = 10
print(point1.x) // outputs 1
print(point2.x) // outputs 10
// reference type
class PointClass {
var x: Int
var y: Int
init(x: Int, y: Int) {
self.x = x
self.y = y
}
}
var point3 = PointClass(x: 1, y: 2)
var point4 = point3 // copies the reference
point4.x = 10
print(point3.x) // outputs 10 (the object changed via the reference)
print(point4.x) // outputs 10