Go Structs: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 5: Line 5:
=Overview=
=Overview=


A <tt>struct</tt> is a user-defined type that contains named fields.  
A <tt>struct</tt> is a user-defined type that contains named fields. <tt>struct</tt>s can also have methods associated with them.


<font color=red>Are all users can define (in terms of types) structs, or there are other user-defined types?</font>
<font color=red>Are all users can define (in terms of types) structs, or there are other user-defined types?</font>

Revision as of 03:12, 30 March 2016

Internal

Overview

A struct is a user-defined type that contains named fields. structs can also have methods associated with them.

Are all users can define (in terms of types) structs, or there are other user-defined types?

Definition

The struct type definition is introduced by the type keyword, to indicated that this is a user-defined type, followed by the type name and the keyword struct. Each field has a name and a type.

type myStruct struct {
    i int
    s string
}

Fields with the same types can be collapsed:

type myStruct struct {
    ...
    i, j, k int
   ...
}

Initialization

Long Variable Declaration

var ms myStruct

If no explicit initialization follows, all the struct's fields are initialized with their zero value.

Short Variable Declaration

Literal

Struct literal initialization:

ms := myStruct{i: 5, s: "something"}

There is a shorter struct literal where the name of the fields are omitted, provided that the order is maintained:

ms := myStruct{5, "something"}

new()

new() initialization:

msPtr := new(myStruct)

Note new() returns a pointer to the structure and not the structure itself.

Fields

Fields can be access with the . operator.

Note that the . operator works with a regular struct variable as well as with a pointer to a struct: the compiler knows how to compensate for both of these cases.

ms := myStruct{1, "s"}
msPtr := new(myStruct)

// valid:
ms.i

// valid:
msPtr.i

A field is always exported by the package it is enclosed in.