Five ways to create Go language variables

  • 2020-10-23 20:08:11
  • OfStack

For those of you with only Python experience, you may not understand the word declaration, so in Python you just use it, and you don't have to declare anything of type.

The Go language is statically typed, and since the compiler checks the type of a variable at compile time, it is required that all variables be explicitly typed.

Variables need to be declared before they are used. Declare a type, and by convention you can only assign a value of that type to this variable.

Declaration 1 generally has four methods, the first two of which can also be used to define constants by changing the keyword var to const.

Type 1: Line 1 declares a variable

var <name> <type>

Where var is the keyword (fixed), name is the variable name, and type is the type.

With var, only the type is specified, but Go implicitly initializes it. For example, string is initialized to an empty string, int is initialized to 0, float is initialized to 0.0, bool is initialized to false, and pointer is initialized to nil.

If you want to initialize as well during the declaration process, you can write this

var name sting = "Python编程"

The complete code in the Go file is as follows. In order not to write repetitive code, only critical code will be used later


package main

import "fmt"

func main() {
 var name string = "Python Programming time "
 fmt.Println(name)
}


From the right value (the value of the right hand side, rvalue), is obviously a string type (to note here that in equivalent Python double quotation marks with single quotes, but in Go double quotes and single quotes is not 1 sample, it must be 1 to use double quotation marks, string, and in single quotation marks said rune type of characters, the following will introduce alone), so it can be simplified as also

var name = "Python编程"

If your right hand value has a decimal point, the compiler will declare your variable float64 without specifying the type, but in many cases, we don't need such high precision (more memory space).

In this case, specify the type and don't be lazy

var rate float32 0.89

Type 2: Multiple variables are declared from 1

Declaring multiple variables, in addition to writing as many lines as above, can be written as follows


var (
 name string
 age int
 gender string
)

Type 3: Declare and initialize a variable

Use := (derived declaration or short type declaration: the compiler automatically deduces the corresponding type of the left value from the right value type.) , you can declare a variable and (explicitly) initialize it.


name := "Python programming "
//  Is equivalent to 
var name string = "Python programming "
//  Is equivalent to 
var name = "Python programming "

But there is a limitation to this approach, which is that it can only be used inside functions

Type 4: Declare and initialize multiple variables

name, age := "wangbm", 28

This method is also often used for the exchange of variables


var a int = 100
var b int = 200
b, a = a, b

Type 5: The new function declares a pointer variable

I'm going to do one more thing here about Pointers.

Variables are divided into two types: ordinary variables and pointer variables

Ordinary variables store the data itself, while pointer variables store the address of the data.

In the following code, age is a common variable with the contents of 28 and ptr is the memory address for the value of the variable age: 0xc000010098


package main
import "fmt"
func main() {
 var age int = 28
 var ptr = &age // & The variable name is followed by the memory address where the variable was fetched 
 fmt.Println("age: ", age)
 fmt.Println("ptr: ", ptr)
}

The output

[

age: 28
ptr: 0xc000010098

]

And the new function that we're talking about here is one of the mole functions in Go.

Using the expression new(Type), an anonymous variable of type Type is created, initialized to zero of type Type, and then the variable address is returned with a pointer of type *Type.


package main
import "fmt"
func main() {
 ptr := new(int)
 fmt.Println("ptr address: ", ptr)
 fmt.Println("ptr value: ", *ptr) // *  This is followed by a pointer variable to represent a value retrieved from a memory address 
}

The output

[

ptr address: 0xc000010098
ptr value: 0

]

There is no difference between creating a variable with new and a normal variable declaration statement, except that you don't need to declare the name of a temporary variable, you can also use new(Type) in an expression. In other words, the new function is similar to a syntactic sugar, rather than a new underlying concept.

These two ways of writing it, you could say, are equivalent


//  use  new
func newInt() *int {
 return new(int)
}
//  Use the traditional way 
func newInt() *int {
 var dummy int
 return &dummy
}

In either case, variables/constants can only be declared once, and if declared multiple times, an error will result from compilation.

There are exceptions, however, which refer to a special variable: an anonymous variable, also known as a placeholder, or an empty identifier, represented by an underscore.

Anonymous variables have the following advantages:

No memory allocated, no memory occupied You don't have to struggle with naming useless variables There is no problem with multiple statements

Usually we use anonymous receiving to receive values that must be received, but are not used.


func GetData() (int, int) {
 return 100, 200
}
func main(){
 a, _ := GetData()
 _, b := GetData()
 fmt.Println(a, b)
}

Supplement: This content mainly describes the five characteristics of GO language speed:

Value storage (effective value processing and value storage, less memory consumption); Function call (using Inlining inline optimization technique) Mandatory garbage collection mechanism (escape analysis, if no reference, then recycling); Go process Stack management (if the old memory is too small, the new large stack is reallocated and the old content is copied to the new content)

conclusion

Above is this site to introduce you to the Go language 5 variable creation methods, I hope to help you!


Related articles: