1. Go's switch is more general than C's. The expressions need not be constants or even integers, the cases are evaluated top to bottom until a match is found. ('break' is not necessary)
func unhex(c byte) byte {
switch {
case '0' <= c && c <= '9':
return c - '0'
case 'a' <= c && c <= 'f':
return c - 'a' + 10
case 'A' <= c && c <= 'F':
return c - 'A' + 10
}
return 0
}
2. Go's switch is more general than C's. The expressions need not be constants or even integers, the cases are evaluated top to bottom until a match is found. ('break' is not necessary)
func unhex(c byte) byte {
switch {
case '0' <= c && c <= '9':
return c - '0'
case 'a' <= c && c <= 'f':
return c - 'a' + 10
case 'A' <= c && c <= 'F':
return c - 'A' + 10
}
return 0
}
3. Note that, unlike in C, it's perfectly OK to return the address of a local variable; the storage associated with the variable survives after the function returns.
func NewFile(fd int, name string) *File {
if fd < 0 {
return nil
}
f := File{fd, name, nil, 0}
return &f
}
4. There are major differences between the ways arrays work in Go and C. In Go,
• Arrays are values. Assigning one array to another copies all the elements.
• In particular, if you pass an array to a function, it will receive a copy of the array, not a pointer to it.
• The size of an array is part of its type. The types [10]int and [20]int are distinct.
The value property can be useful but also expensive; if you want C-like behavior and efficiency, you can pass a pointer to the array.
func Sum(a *[3]float64) (sum float64) {
for _, v := range *a {
sum += v
}
return
}
array := [...]float64{7.0, 8.5, 9.1}
x := Sum(&array) // Note the explicit address-of operator
5. In a := declaration a variable v may appear even if it has already been declared, provided:
• this declaration is in the same scope as the existing declaration of v (if v is already declared in an outer scope, the declaration will create a new variable §),
• the corresponding value in the initialization is assignable to v, and
• there is at least one other variable in the declaration that is being declared anew.
f, err := os.Open(name)
d, err := f.Stat()
6. The rule about pointers vs. values for receivers is that value methods can be invoked on pointers and values, but pointer methods can only be invoked on pointers.