clearly express the logic, leave the physical execution detail to compiler and runtime.
Java
Java can make the variable final, but not const
Java pass every non-primitive by pointer, which makes it mutable
class Money {
public int Amount;
public String Unit;
}
void transfer(final Money m) {
// although m is final, assignment like m.Amount = 100 is still valid
}
Go
Go can not make variable final or const
Go will copy struct automatically, which makes it immutable
type Money struct {
Amount int
Unit string
}
func transfer(m Money) {
// m is a copy
}
func transfer(m *Money) {
// m is a reference to same value, mutable
}
Shiti
YinGuo defined two keyword var and let. Func argument is const by default, unless otherwise specified.
We do not need to worry about the argument is passed as a copy of value or reference some memory on the heap. The code should focus on the logic, not execution details.
func OpenFile(file string) File {
// func argument is const by default
}
add var to make the func argument a variable
type Times(arr var []int, multiplier int) {
// multiplier = 3 will compile fail, because multiplier is not variable but const
for i, e := range arr {
arr[i] = e * multiplier
}
}
use let to define a const in block scope
type Times(arr var []int, multiplier int) {
for i, e := range arr {
let newValue = e * multiplier
arr[i] = newValue
}
}
variable is mutable
type Times(arr var []int, multiplier int) {
for i, e := range arr {
var newValue = e
newValue = newValue * multiplier
arr[i] = newValue
}
}
GOAL
clearly express the logic, leave the physical execution detail to compiler and runtime.
Java
Go
Shiti
YinGuo defined two keyword
var
andlet
. Func argument is const by default, unless otherwise specified.We do not need to worry about the argument is passed as a copy of value or reference some memory on the heap. The code should focus on the logic, not execution details.
add
var
to make the func argument a variableuse let to define a const in block scope
variable is mutable