search
HomeBackend DevelopmentGolangDetailed explanation of Go language structure and initialization graphic and text

Detailed explanation of Go language structure and initialization graphic and text

Go supports user-defined types through type aliases (alias types) and structures.

Structure is a composite type. When you need to define a type, which consists of a series of attributes, each attribute has its own type and value, you should use a structure, which gathers data together.

Structures are also value types, so you can use the new function to create

The data that make up the structure type become fields. Each field has a type and a name; within a structure, field names must be unique.

1. Structure definition

The general way of defining a structure is as follows:

type identifier struct {   
   field type1
    field type2}

type T struct {a, b int} is also a legal syntax. It is more suitable for simple structures.

The fields in the structure have names, such as field1, field2, etc. If the fields are never used in the code, Then you can name it _.

The naming of structure types and fields follows visibility rules, so there may be some fields of a structure type that are exported, while others are not.

The fields of the structure can be of any type, even the structure itself, or it can be a function or interface. You can declare a variable of a structure type and then assign values ​​to its fields like this:

var s T
s.a = 5
s.b = 8

An array can also be regarded as a structure type, but it uses subscripts instead of named fields

Second, initialization

#Method 1: Declare the structure through var

In Go language When a variable is declared, the system will automatically initialize its default value. For example, int is initialized to 0 and the pointer is nil.
The var declaration will also allocate memory for structure type data, so we can directly assign values ​​to its fields after declaring var s T like in the previous code.

Method 2: Use new

Use the new function to allocate memory to a new structure variable. It returns a pointer to the allocated memory: var t *T = new(T).

type struct1 struct {
    i1 int
    f1 float32
    str string}func main() {
    ms := new(struct1)
    ms.i1 = 10
    ms.f1 = 15.5
    ms.str= "Chris"

    fmt.Printf("The int is: %d\n", ms.i1)
    fmt.Printf("The float is: %f\n", ms.f1)
    fmt.Printf("The string is: %s\n", ms.str)
    fmt.Println(ms)
}

Same as object-oriented languages, you can use the dot operator to assign values ​​to fields: structname.fieldname = value.

Similarly, you can use the dot operator to get the value of the structure field: structname.fieldname.

Method 3: Use literals

type Person struct {
    name string
    age int
    address string
}

func main() {
    var p1 Person
    p1 = Person{"lisi", 30, "shanghai"}   //方式A
    p2 := Person{address:"beijing", age:25, name:"wangwu"} //方式B
    p3 := Person{address:"NewYork"} //方式C
}

In (Method A), the values ​​must be given in the order in which the fields are defined in the structure. (Method B) adds the field name and colon in front of the value. In this method, the order of the values ​​does not have to be consistent, and some fields can be ignored, just like (Method C).

In addition to the above three methods, there is a shorter and more common way to initialize the structure entity, as follows:

ms := &Person{"name", 20, "bj"}
ms2 := &Person{name:"zhangsan"}

&Person{a, b, c} is an abbreviation, The bottom layer will still call new(), where the order of the values ​​must be written in the order of the fields. It can also be written by adding the field name and colon in front of the value (see methods B and C above).

The expressions new(Type) and &Type{} are equivalent.

3. The difference between several initialization methods

So far, we have learned about three ways to initialize a structure:

//第一种,在Go语言中,可以直接以 var 的方式声明结构体即可完成实例化
var t T
t.a = 1
t.b = 2

//第二种,使用 new() 实例化
t := new(T)

//第三种,使用字面量初始化
t := T{a, b}
t := &T{} //等效于 new(T)

Using var t T will allocate memory for t and zero-value the memory, but the type of t at this time is T

When using the new keyword t := new(T) , the variable t is a pointer to T

From the memory layout, we can see the difference between these three initialization methods:

Use var statement:

Detailed explanation of Go language structure and initialization graphic and text

Use new to initialize:

Detailed explanation of Go language structure and initialization graphic and text

Use structure literal to initialize:

Detailed explanation of Go language structure and initialization graphic and text

Let’s look at a specific example:

package main
import "fmt"

type Person struct {
 name string
 age int
}

func main() {
 var p1 Person
 p1.name = "zhangsan"
 p1.age = 18
 fmt.Printf("This is %s, %d years old\n", p1.name, p1.age)

 p2 := new(Person)
 p2.name = "lisi"
 p2.age = 20
 (*p2).age = 23 //这种写法也是合法的
 fmt.Printf("This is %s, %d years old\n", p2.name, p2.age)

 p3 := Person{"wangwu", 25}
 fmt.Printf("This is %s, %d years old\n", p3.name, p3.age)
}

Output:

This is zhangsan, 18 years old
This is lisi, 23 years old
This is wangwu, 25 years old

In the second case of the above example, although p2 is a pointer type, we can still like p2.age = 23 For assignment, there is no need to use the -> operator like in C, Go will automatically convert it.

Note that you can also use the * operator to get the content pointed to by the pointer first, and then assign it: (*p2).age = 23.

Memory layout of structure

Go 语言中,结构体和它所包含的数据在内存中是以连续块的形式存在的,即使结构体中嵌套有其他的结构体,这在性能上带来了很大的优势。不像 Java 中的引用类型,一个对象和它里面包含的对象可能会在不同的内存空间中,这点和 Go 语言中的指针很像。

下面的例子清晰地说明了这些情况:

type Rect1 struct {Min, Max Point }
type Rect2 struct {Min, Max *Point }

Detailed explanation of Go language structure and initialization graphic and text

更多go语言知识请关注PHP中文网go语言教程栏目。

The above is the detailed content of Detailed explanation of Go language structure and initialization graphic and text. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Golang's Impact: Speed, Efficiency, and SimplicityGolang's Impact: Speed, Efficiency, and SimplicityApr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

C   and Golang: When Performance is CrucialC and Golang: When Performance is CrucialApr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang in Action: Real-World Examples and ApplicationsGolang in Action: Real-World Examples and ApplicationsApr 12, 2025 am 12:11 AM

Golang excels in practical applications and is known for its simplicity, efficiency and concurrency. 1) Concurrent programming is implemented through Goroutines and Channels, 2) Flexible code is written using interfaces and polymorphisms, 3) Simplify network programming with net/http packages, 4) Build efficient concurrent crawlers, 5) Debugging and optimizing through tools and best practices.

Golang: The Go Programming Language ExplainedGolang: The Go Programming Language ExplainedApr 10, 2025 am 11:18 AM

The core features of Go include garbage collection, static linking and concurrency support. 1. The concurrency model of Go language realizes efficient concurrent programming through goroutine and channel. 2. Interfaces and polymorphisms are implemented through interface methods, so that different types can be processed in a unified manner. 3. The basic usage demonstrates the efficiency of function definition and call. 4. In advanced usage, slices provide powerful functions of dynamic resizing. 5. Common errors such as race conditions can be detected and resolved through getest-race. 6. Performance optimization Reuse objects through sync.Pool to reduce garbage collection pressure.

Golang's Purpose: Building Efficient and Scalable SystemsGolang's Purpose: Building Efficient and Scalable SystemsApr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Apr 02, 2025 pm 05:24 PM

Confused about the sorting of SQL query results. In the process of learning SQL, you often encounter some confusing problems. Recently, the author is reading "MICK-SQL Basics"...

Is technology stack convergence just a process of technology stack selection?Is technology stack convergence just a process of technology stack selection?Apr 02, 2025 pm 05:21 PM

The relationship between technology stack convergence and technology selection In software development, the selection and management of technology stacks are a very critical issue. Recently, some readers have proposed...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment