Kingsdz
(Kingsdz)
April 4, 2018, 3:56am
1
Hi guys !
I am new to Golang. I just can’t understand and self-explain this code.
type Book struct {
name string
}
func main() {
a := &Book{name: “hehe”}
b := &string(“hehe”)
fmt.Println(a) // Why work?
fmt.Println(b) // Why fail?
}
What is differences between struct and string (Pointer, Variable) when they initialize?
Thanks. ^^
lutzhorn
(Lutz Horn)
April 4, 2018, 6:07am
2
Book{name: "hehe"}
creates a new Book
instance, using &
on it will givce you the address. Here Book{...}
is a constructor .
struct
is not a constructor, it is a conversion expression . It takes an existing value ("hehe"
) and tries to convert it to a string
. You can’t combine the reference &
with a conversion.
4 Likes
Kingsdz
(Kingsdz)
April 5, 2018, 2:11am
3
Yah. I missed that point.
Thank you and have a good day.
vitr
(Vitaliy Ryepnoy)
April 5, 2018, 4:14am
4
You can’t have a pointer to a string, but you can still have pointers to string variables in Go, e.g.
b := string("hehe")
PointerToStringVar := &b
the full example is here https://goplay.space/#aQZ8yWghJ8N
3 Likes
system
(system)
Closed
July 4, 2018, 4:14am
5
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.