Go Structs: Difference between revisions
Jump to navigation
Jump to search
Line 41: | Line 41: | ||
==Short Variable Declaration== | ==Short Variable Declaration== | ||
Struct literal initialization: | |||
<pre> | |||
ms := myStruct{i: 5, s: "something"} | |||
</pre> | |||
<tt>[[Go_Built-In_Function_new|new()]]</tt> initialization: | <tt>[[Go_Built-In_Function_new|new()]]</tt> initialization: | ||
Line 49: | Line 55: | ||
Note <tt>new()</tt> returns a pointer to the structure and not the structure itself. | Note <tt>new()</tt> returns a pointer to the structure and not the structure itself. | ||
=Struct Literals= | =Struct Literals= |
Revision as of 02:16, 30 March 2016
Internal
Overview
A struct is a user-defined type that contains named fields.
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
Struct literal initialization:
ms := myStruct{i: 5, s: "something"}
new() initialization:
msPtr := new(myStruct)
Note new() returns a pointer to the structure and not the structure itself.
Struct Literals
Fields
A field is always exported by the package it is enclosed in.