Junior — Middle
Can you explain what data types are passed by reference in programming languages?
sobes.tech AI
Answer from AI
In programming languages, pass-by-reference types mean that when a variable is passed to a function or method, a reference (pointer) to the original data is passed, not a copy of the value. Changes within the function will affect the original object.
In Go, primitive types (int, float, bool) are passed by value, while complex types such as slices, maps, pointers, channels, and interfaces are passed by reference.
Example of passing a slice by reference:
func modifySlice(s []int) {
s[0] = 100
}
func main() {
nums := []int{1, 2, 3}
modifySlice(nums)
fmt.Println(nums) // Will output [100 2 3]
}
Here, the function receives a reference to the slice, so changes inside the function are reflected in the original slice. This allows efficient handling of large data structures without copying.