Why can't a string be nil in Go?

前端 未结 4 1044
予麋鹿
予麋鹿 2021-02-06 21:11

The program available on The Go Playground reads

package main

import \"fmt\"

func main() {
    var name string = nil
    fmt.Println(name)
}

4条回答
  •  没有蜡笔的小新
    2021-02-06 22:12

    Because Golang string is a read-only slices of bytes.

    However, a pointer to a string (*string) can be nil:

    var s *string
    s = nil
    readonly := "readonly"
    s = &readonly
    dereference := *s
    

    https://dhdersch.github.io/golang/2016/01/23/golang-when-to-use-string-pointers.html

提交回复
热议问题