Golang: Struct

By Xah Lee. Date: . Last updated: .

What is Struct

Struct is user-defined type. It defines a collection of “fields”, each field is a name and a value of a specific type.

Struct is similar to golang map, except that number of keys and key names are fixed.

Once you defined a struct type (with a given name), you can create struct of that name.

Note, struct is very important in golang. Because “object oriented programing”'s concept of interface and methods, are based on it.

Define a New Struct Type

Here's how to define a struct.

type Name struct { fieldName1 fieldType1; fieldName2 fieldType2; etc }

The fieldName1 or fieldName2 etc each can be a list of names separated by comma.

Here's how to create a struct you just defined:

Name{fieldName1:val1, fieldName2:val2, etc}

or

Name{val1, val2, etc}

package main

import "fmt"

// define a struct named PP
type PP struct {
	x int
	y int
}

func main() {
	// create a struct PP
	var x PP = PP{1, 2}

	// print struct with value only
	fmt.Printf("%v\n", x) // {1, 2}

	// print struct with field name and value
	fmt.Printf("%+v\n", x) // {x:1 y:2}
}

Create Struct: Struct Literals

A struct literal lets you create a value of a given struct type.

For example, if you have this struct type

type PP struct{ x, y int }

you can create a value by

var p1 = PP{x:3, y:4}

or

var p1 = PP{}

and use PP.x=3 etc to fill the field values later.

package main

import "fmt"

// define a struct type
type PP struct{ x, y int }

func main() {

	// create a struct of PP
	var p1 = PP{x: 3, y: 4}

	fmt.Printf("%#v\n", p1) // main.PP{x:3, y:4}

}

If a key is omitted, it defaults to its zero value. [see Golang: Zero Value]

package main

import "fmt"

type PP struct{ x, y int }

func main() {
	var p1 = PP{y: 4}
	fmt.Printf("%#v\n", p1) // main.PP{x:0, y:4}
}

Alternatively, you can omit keys and only use values.

var p1 = PP{3, 4}

If you omit keys, you must omit all keys, and the order must be the same order as in the struct definition.

package main

import "fmt"

type PP struct{ x, y int }

func main() {
	var tt = PP{3, 4}
	fmt.Printf("%#v\n", tt) // main.PP{x:3, y:4}
}

Get/Set Field Value

struct_name.field_name
Return the value
struct_name.field_name = val
Set new value
package main

import "fmt"

type PP struct {
	x int
	y int
}

func main() {

	v := PP{3, 4}

	// get a field value
	fmt.Println(v.x) // 3

	// set a field value
	v.x = 4
	fmt.Println(v.x) // 4
}

Print Struct