Strings within a struct can't be nil?

1,833 views
Skip to first unread message

josvazg

unread,
Nov 25, 2010, 9:40:39 AM11/25/10
to golang-nuts
Why is it that strings within a struct can't be set to nil?
In the samle below if I uncomment the str2 and its intiialization to
nil the compiler complains:

"structest.go:16: cannot use nil as type string in field value"

CODE...
_____________________________
package main

import (
"fmt"
"unsafe"
)

type somestruct struct {
someint int
somestr string
//str2 string
}

func main() {
fmt.Println("Hello, 世界")
s:=somestruct{1,"kk"/*,nil*/}
fmt.Println("somestruct:",s,"size",unsafe.Sizoef(s))
s.somestr="sdfs"
fmt.Println("somestruct:",s,"size",unsafe.Sizoef(s))
}

roger peppe

unread,
Nov 25, 2010, 9:43:31 AM11/25/10
to josvazg, golang-nuts
nil is not a valid value for a string.

use "" instead.

André Moraes

unread,
Nov 25, 2010, 9:47:07 AM11/25/10
to golang-nuts
nil is valid for pointers or slices.

you can use *string
Reply all
Reply to author
Forward
0 new messages