What is "&" before struct?

programs:=&struct{field1 int}{15}
What does & mean in this statement? If I write it in other data struct I get error.
example:=&string{} it’s error

The ampersand means to take the address of something and the result is a pointer. For example:

package main

import "fmt"

func main() {
  s := "Hello"
  f(&s)
  fmt.Println(s)
}

func f(p *string) {
  *p += ", world!"
}

The way you write a struct literal is structType{field1: field1Value, field2, field2Value}. For example:

// myStruct is a defined type because we gave it a name:
type myStruct struct {
  a int
  b int
}

func main() {
  s := myStruct{a: 0, b: 1}
  // do something
}

Anonymous structs aren’t given names (that’s what makes them “anonymous”) so in place of structName, you repeat the type like you have in &struct{field1 int}{15}. Maybe you already knew this, but I wanted to explain the double struct{...}{...} syntax just in case.

Strings are not structs, just like numbers are not structs or strings, so you do not use curly braces to define them, you use double quotes or backticks:

a := "My string"
b := `"My" string`
1 Like

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