Brother even go language training share struct structure

Source: Internet
Author: User
Tags uppercase letter

Brother even go language training Course System Design framework includes the basic language of the blockchain go language, blockchain backend technology system, blockchain public chain, blockchain distributed application development and other content, as well as to the final interview guidance and project combat. The course was carefully built by Tsinghua University's Microsoft Google Teacher team, which lasted half a year and developed together.

Let's introduce the type system of the Go language


Type systems in the Golang


Type system refers to the type architecture of a language. A typical type system typically contains the following basic elements:


Q Basic types, such as Byte, int, bool, float, etc.;


Q composite types, such as arrays, structures, pointers, etc.;


Q can point to the type of any object (any type);


Q-value semantics and referential semantics;


Q Object-oriented, i.e. all types with object-oriented features (such as member methods);


Q interface.


Most types in the go language are value semantics and can contain corresponding action methods. You can "add" new methods to any type (including built-in types) when needed. When implementing an interface, it is not necessary to inherit from the interface (in fact, the go language does not support the inheritance syntax in object-oriented thinking at all), it only needs to implement all the methods required by that interface. Any type can be referenced by any type. The any type is an empty interface, or interface{}.


What is a structural body?


A struct (struct) is a user-defined type that represents a collection of several fields that can be used to describe an entity object, similar to class in Java, and is the underlying type of Golang object-oriented programming.


The concept of architecture in software engineering is called ADT (abstract data type: Abstractdatatype), an old term. In C + + It also exists, and the name is also a struct, in an object-oriented programming language, as with a lightweight class without methods. Because there is no concept of class in the go language, the structure in go has a more important position.


How to define a struct


typecoordinatestruct{


X,yfloat32


}


Syntax: typestruct{}


The code above defines a struct named coordinate, which contains two float32 of variable x, y, which can be used to represent a planar coordinate.


Add Object method


Other classic object-oriented languages such as java,c#, which define object methods, are included in the definition of class, such as


publicclasscoordinate{


Publicfloatx{get;set;}


Publicfloaty{get;set;}


Print coordinates


Publicvoidgetcoordinate () {


Console.WriteLine ("(" +this. X+ "," +this. y+ ")");


}


}


In the Go language, object methods are added outside the structure definition


typecoordinatestruct{


X,yfloat32


}


Print coordinates


Func (Coo*coordinate) getcoordinate () {


Fmt. Printf ("(%.2f,%.2f) \ n", COO. X,coo. Y


Return


}


Where the Func keyword follows (coo*coordinate), indicating that the function passed in a pointer to coordinate, which can be manipulated by the pointer variable COO to manipulate the value of the struct.


Initialization of several structure bodies


First, by creating the structure by the original field order


Packagemain


Import


"FMT"


)


Funcmain () {


p0:=coordinate{1,2}


P0. Getcoordinate ()


}


Output: (1.00,2.00), where x=1,y=2


Second, initialize according to the custom field order


Packagemain


Import


"FMT"


)


Funcmain () {


P0:=coordinate{y:1,x:2}


P0. Getcoordinate ()


}


Output: (2.00,1.00), where X=2,y=1


Third, create through the new function


Packagemain


Import


"FMT"


)


Funcmain () {


Allocates memory to the struct P2 variable, which returns a pointer to the allocated memory


p0:=new (coordinate)


P0. X=1


P0. y=2


P0. Getcoordinate ()


}


Output: (1.00,2.00), where x=1,y=2


where p0:=new (coordinate) is equivalent to the following notation


P3:=&coordinate{x:1,y:2}


p3:=&coordinate{1,2}


Compare three ways to create


Among them, the first and the second, P0 are one instance of type coordinate, and the third p0 is a pointer to coordinate, equivalent to varp0*coordinate=new (coordinate)


Typically after a struct definition such as Typetstruct{a,bint}


It is customary to use t:=new (T) to allocate memory to the struct variable, which returns a pointer to the allocated memory. The variable t is a pointer to T, at which point the value of the struct field is the 0 value of the type to which they belong.


Declaring Vartt also allocates memory to T, and 0 values memory, but this time t is type T. In both of these ways, T is usually called an instance of type T (instance) or an object. Vart*t=new (t) is equivalent to T:=new (t).


Analyze the above conclusions through code


Packagemain


Import


"FMT"


)


Funcmain () {


p0:=coordinate{1,2}


Allocates memory to the struct P2 variable, which returns a pointer to the allocated memory


p2:=new (coordinate)


P2. X=1


P2. y=2


P3:=&coordinate{x:1,y:2}


p4:=&coordinate{1,2}


Fmt. Println ("-------output p0-------")


Fmt. Printf ("%v\n%t\n", P0,p0)


Fmt. Println ("-------output p2-------")


Fmt. Printf ("%v\n%t\n", P2,P2)


Fmt. Println ("-------output p3-------")


Fmt. Printf ("%v\n%t\n", P3,P3)


Fmt. Println ("-------output P4-------")


Fmt. Printf ("%v\n%t\n", P4,P4)


}


Output:


-------Output P0-------


{12}


Coordinate


-------output P2-------


&{12}


*coordinate


-------Output P3-------


&{12}


*coordinate


-------output P4-------


&{12}


*coordinate


As you can see, p2,p3,p4 are a pointer variable


Object methods for adding value copies


Just now, add an object method that can be created with func (t*t) functionname (), where T is a pointer variable. We can also add an object method by means of a value copy, with the syntax of Func (TT) functionname ()


Packagemain


Import


"FMT"


)


typecoordinatestruct{


X,yfloat32


}


Func (Coo*coordinate) getcoordinate () {


Fmt. Printf ("(%.2f,%.2f) \ n", COO. X,coo. Y


Return


}


Value Copy Object method


Func (coocoordinate) SetPosition01 (afloat32,bfloat32) {


Coo. X=a


Coo. Y=b


}


Pointer Variable Object methods


Func (coo*coordinate) SetPosition02 (afloat32,bfloat32) {


Coo. X=a


Coo. Y=b


}


Funcmain () {


p0:=coordinate{1,2}


Fmt. Print ("SetPosition02 before Call:")


P0. Getcoordinate ()


P0. SETPOSITION02 (0,0)


Fmt. Print ("SetPosition02 after Call:")


P0. Getcoordinate ()


}


Output:


SetPosition01 before call: (1.00,2.00)


After SetPosition01 call: (1.00,2.00)


SetPosition02 before call: (1.00,2.00)


After SetPosition02 call: (0.00,0.00)


As can be seen from the program output, the call to the SetPosition01 method, a value copy occurs, even if the value of the COO is changed within the method, the value of the external p0 is not changed. In the SetPosition02 method, the COO is a pointer to the P0 address, and since the value of x, Y is modified by a pointer variable, the value of the external p0 is modified to (0,0) after the call is complete.


anonymous struct


Packagemain


Import


"FMT"


)


Funcmain () {


p_3d:=struct{


X,y,zfloat32


}{1,2,3}


Fmt. Println ("-------output p_3d-------")


Fmt. Printf ("%v\n%t\n", p_3d,p_3d)


}


Output:


-------Output p_3d-------


{123}


Struct{xfloat32; Yfloat32; Zfloat32}


P_3d as an anonymous struct containing three x, Y, z variables


Golang constructor function?


There is no concept of constructors in the go language, the creation of objects is usually done by a global creation function, named by Newxxx, to represent "constructors":


It's all very natural, and developers don't need to analyze how much is going on behind the scenes after using new. In the go language, everything that's going to happen is directly visible.


Funcnewrect (X,y,width,heightfloat64) *rect{


Return&rect{x,y,width,height}


}


Variable, method visibility


The go language is very stingy with keyword additions, and there are no keywords such as private, protected, public. To make a symbol visible to other packages (that is, accessible), you need to define the symbol to start with an uppercase letter, such as:


typerectstruct{


X,yfloat64


Width,heightfloat64


}


In this way, the member variables of the RECT type are all exported and can be accessed by all other code referencing the package where the RECT resides. The accessibility of member methods follows the same rules, such as:


Func (R*rect) area () float64{


Returnr. Width*r.height


}


In this way, the area () method of Rect can only be used within the same package as the type.


One thing to note is that the accessibility of symbols in the Go language is package-level rather than type-level. In the example above, although area () is an internal method of rect, it can be accessed by other types in the same package. This kind of accessibility control is very rough, very special, but very practical. If the accessibility of the Go language symbol is type-level, you need to add a keyword like friend to indicate that two classes are friends and can access each other's private members.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.