Pointer to struct vs Pointer to string

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. ^^

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.


Yah. I missed that point.
Thank you and have a good day.

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


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.