美文网首页
const in golang 2023-09-13

const in golang 2023-09-13

作者: 9_SooHyun | 来源:发表于2023-09-12 11:53 被阅读0次

    why only basic data type support const declaration in golang

    为什么golang的const只支持基本数据类型如int/string,而不支持复杂的数据类型

    个人认为,核心原则是,const只应当修饰最简单的只有一层的数据结构。当数据结构存在多层引用时,如果要达到完全的const,必须递归地把所有被引用的底层数据结构也进行const。一旦数据结构层次过多,将形成一个 const hell

    基本数据类型的const

    // You can edit this code!
    // Click here and start typing.
    package main
    
    import "fmt"
    
    func main() {
        // c 不可变
        const c = "const_str"
        // 值传递赋值给a, a可变
        a := c
        fmt.Printf("a'address before modified is %p\n", &a)
        // 修改a
        a = "new_str"
        fmt.Printf("a'address after modified is %p\n", &a)
    
        // c is not changed, so b's value is the same as "const_str"
        b := c
        fmt.Println(a, b, c)
    }
    
    

    社区讨论

    https://github.com/golang/go/issues/6386

    take a look at Slice/Map/Struct

    Slice的数据结构本身是一个结构体,携带有指向底层Array的指针,len和cap

    简要示例:

    type slice struct {
        array unsafe.Pointer
        len   int
        cap   int
    }
    

    类似地,Map的数据结构本身是一个结构体,也携带一个指针

    如果Slice/Map可以被const修饰,也就是struct可以被const修饰

    questions about const slices by cznic:

    // You can edit this code!
    // Click here and start typing.
    package main
    
    import "fmt"
    
    func main() {
        // if const slice is allowed, then the under struct of c is never modified
        const c = []byte{1}
        a := c
        // a and c use the same backing array, so after a changes the value at 0 position, c's value changed while under struct of c stays
        // c 的结构体成员kv确实是不变的,但是c的成员指针指向底层array改变了,于是对于程序员来说,c并不const,或者说并没有彻底const
        // 这样一来,const的语意就confused了
        a[0] = 42
    
        b := c
        fmt.Println(b[0] == 1)  
        // The above can print 'true' only if the c's backing array is copied in assignment to 'a',
        // however the const declaration gives an illusion of always using the same backing array
    }
    
    

    不难发现,核心原则是,const只应当修饰最简单的只有一层的数据结构。当数据结构存在多层引用时,如果要达到完全的const,必须递归地把所有被引用的底层数据结构也进行const。一旦数据结构层次过多,将形成一个 const hell

    Robert Griesemer comments on this

    Some comments:

    1. This is neither a defect of the language nor the design. The language was
      deliberately designed to only permit constant of basic types.
    2. The implications of such a change are much more far-fetching than meets the eye:
      there are numerous open questions that would have to be answered satisfactorily; and I
      don't think we are there yet.
      For instance, if we allow such constants, where is the limit? Do we allow constant maps?
      What about constant channels? Constant pointers? Is it just a special case for slices?
      etc.
      A first step might be to allow constant arrays and structs as long as they are only
      composed of fields that can have constant types themselves.
      An even smaller step (which I do think we should do) is to make "foo"[i] a constant if i
      is a constant (right now it's a non-constant byte).
      Finally, note that it's often not very hard for a compiler to detect that a
      package-level variable is never modified. Thus, an implementation may choose to optimize
      the variable initialization and possibly compute it compile time. At this point, the
      const declaration only serves as documentation and for safety; there's no performance
      loss anymore.
      But again, we have tried to keep the type system (incl. what constants are) relatively
      simple so that it doesn't get into the way. It's not clear the benefits are worth the
      price in additional complexity.

    It's not clear the benefits are worth the price in additional complexity.

    相关文章

      网友评论

          本文标题:const in golang 2023-09-13

          本文链接:https://www.haomeiwen.com/subject/hmoyvdtx.html