The difference between Go and C-like language

1Go'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

}


2Go'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

}


3Note 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.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值