Go to initialize a variable's moves

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The various flags at the beginning of the year have been forget all about by me. 2018 has passed half, finally began the third article, the output plan for the whole year 30, only 27 left, I have "confidence to complete" the rest of the section.

Beginning in 2018, starting from PHP to go to the development direction, although the learning route is not very steep, but the process encountered a lot of pits and interesting places, can't help but want to summarize share to everyone. Let's talk about some of the ways to initialize variables in go today.

Moves to initialize value types in Go

The data types of Golang can be divided into: value types and reference types , let me summarize the initialization of the value type in Go (in string case):

var a1 stringfmt.Printf("a1: %#v \n", a1) // a1: ""var a2 *stringfmt.Printf("a2: %#v \n", a2) // a2: (*string)(nil)// panic: runtime error: invalid memory address or nil pointer dereference//fmt.Printf(**"a2: %#v \n"**, *a2)a3 := new(string)fmt.Printf("a3: %#v \n", a3) // a3: (*string)(0xc42000e200)fmt.Printf(**"a3: %#v \n"**, *a3) // a3: ""a4 := "hello"fmt.Printf("a4: %#v \n", a4) // a4: "hello"a5 := string("hello")fmt.Printf("a5: %#v \n", a5) // a5: "hello"a6 := &a5fmt.Printf("a6: %#v \n", a6) // a6: (*string)(0xc42000e1e0)// 报错,cannot make type string//a7 := make(string, 1)// 报错,cannot take the address of string("hello")//a8 := &string("hello")

The comments section is the output of the information, you can see that some results hit out is a value, there is a pointer. This part of the focus I just want to illustrate two points:

    1. Go automatically initializes the declaration variable to a value of 0, the so-called 0 value is: int is 0,string is a null character, BOOL is false, etc.
    2. For a variable created by new, it is a pointer to a variable declared by Var, and Var declares a variable that is only nil. and new (string) allocates a piece of memory to string, initialized to 0. It can be understood by the above comments of the error message.

Go to initialize a reference type of moves

That's what I'm trying to say, there are only three types of references in go::: Map:::: Slice:::: Channel::, here's an example of slice.

var s1 []stringfmt.Printf("s1: %#v\n", s1) // s1: []string(nil)s1 = append(s1, "hello")fmt.Printf("s1: %#v\n", s1) // s1: []string{"hello"}var s2 *[]stringfmt.Printf("s2: %#v\n", s2) // s2: (*[]string)(nil)s3 := []string{"a", "b", "c"}fmt.Printf("s3: %#v\n", s3) // s3: []string{"a", "b", "c"}s4 := &[]string{}fmt.Printf("s4: %#v\n", s4) // s4: &[]string{}s5 := &s3fmt.Printf("s5: %#v\n", s5) // s5: &[]string{"a", "b", "c"}s6 := new([]string)fmt.Printf("s6: %#v\n", s6) // s6: &[]string(nil)// first argument to append must be slice; have *[]string//s6 = append(s6, "hello") // 这是一个空引用的指针,所以报错s7 := make([]string, 0)fmt.Printf("s7: %#v\n", s7) // s7: []string{}// 有毛病才用这种方式s8 := new([]string)*s8 = make([]string, 0)fmt.Printf("s8: %#v\n", s8) // s8: &[]string{}arr := [5]string{"a", "b", "c"}s9 := arr[:]fmt.Printf("s9: %#v\n", s9) // s9: []string{"a", "b", "c", "", ""}

Here I focus on the analysis of S6, S7, S8 Three kinds of initialization methods. Say S6 first, use new.

New (t) allocates a single piece of memory for each of the newer type T, initialized to 0 and returns a memory address of type *t: This method returns a pointer to an address of type T, with a value of 0
Here the so-called value is 0, not the value 0, but the default value of Go 0, corresponding to:: Slice:: nil.

There is absolutely no way to initialize in go:: Slice::, why? Let me put it briefly here, because go:: Slice:: Is defined as follows:

type slice struct{    array unsafe.Pointer    len   int    cap   int}

If you use new because the memory address of the T is returned , unable to complete the right:: Slice:: Initialization, can not let slice normal use, want to let him work normally, you have to do the same way as S8, and then use make corresponding T to initialize. If you do, do you think there is something wrong to use the way?

the initialization of the slice requires the value of Len, cap to be initialized, and the array to point to a pointer to an array. After these initializations are completed, the slice can be used normally.

Summarize

The initialization of the custom structure is the same as the initialization of the above string, with the map, channel, and slice. You can write your own code and try it.

    • Remember that make is only used for Map,slice and channel, and does not return pointers.
    • To get an explicit pointer, use new to assign, or explicitly use the address of a variable.

Next things you plan to share:

    1. go in the knowledge of values, references, pointers, the focus is the parameter of the function of the method
    2. go:: Slice:: With:: array:: Intimacy
    3. go in the knowledge of the interface, from:: Sort:: The source angle to introduce
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.