Go example Tour (top)

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

Introduce

This is from go by example example, spent a few days to write these examples, feel very helpful to me, for beginners, my advice is to look at this go to the book from beginning to end, and then look at these examples, each of the examples are hand-knocking, for your help is still very big. In the process of knocking these examples, there are some questions, there are some knowledge of the expansion, so summed up this article.

You don't know. PrintOut

In go, the FMT package is very powerful, it provides printing methods such as PRINT,PRINTLN, supports formatted output similar to C, and most importantly, the FMT package can identify any type of function is very powerful. Below is the use of FMT to print a custom structure.

package mainimport"fmt"typestruct{    string    int}func main() {    man := custom_struct{"zhang",10}    vars := []string{"first","second","last"}    fmt.Println(man)    fmt.Println(vars)}

The above code can be directly printed custom_struct, but also can directly print the array, etc., the function is very powerful, but few people know that the go language in the interior also has a print,println method for printing output, with few people, These printing methods are typically used for go internal debug and do not support printing custom types.

High-capacity constants

In the go language, numbers can be written directly into exponential form, for example 3e20 , and constants in go can receive values of constant expression of arbitrary precision, such as the following example.

package mainimport"fmt"func main() {    const n = 5000    const d = 3e100 / n    fmt.Println(d)}

The constant D can receive the value of arbitrary precision, in addition to the constant has another feature is that there is no type, can be given by an explicit conversion of the type, or by the context of a constant type, such as assignment operation, function call, then the type of the constant is the assignment operator to the left of the type, Or it becomes the formal parameter type of the function call.

Omnipotent for

In go, the for loop can be a while loop in C, a for loop, a keyword to complete all the looping operations, and a loop operation similar to range in Python.

funcMain () {i: =1Nums: = []int{2, 3, 4}//while Cycle     forI <=3{FMT. PRINTLN (i) i = i +1}//normal for loop     forJ: =7; J <=9; J + + {FMT. Println (J)}//range-based loops     forI,num: =RangeNums {ifnum = =3{FMT. Println ("Index:", i)}}//Dead Loop     for{FMT. Println ("Loop") Break}}

If you can also do this

If statement in general, and C in the use of the if is not very different, except that if support in the go language with an assignment expression in front of the condition, refresh my three view, and there is no question mark in the go like C in the expression, the following is an assignment expression of the IF

func main() {    //这里是可以前置一个赋值表达式的    ifnum9num0 {        fmt.Println(num,"is negative")    elseifnum10 {        fmt.Println(num,"has 1 digit")    else {        fmt.Println(num,"has multiple digits")    }}

Not the same switch

Since the study of Golang, constantly refresh my three views, this and I contact before the C/c++,python difference is not general big Ah, in Go switch also has both normal and abnormal place normal use situation and C switch basically same, But the switch in go does not have the concept of penetrating, meaning that the match to the specified item ends when it stops, no longer down. Switch in Go is not a break that needs to be displayed. In addition, there is no difference between the switch and C, but this is just the normal side of go switch, the abnormal side is the switch of Go support multi-conditional matching, support expression matching.

    Switch  Time. Now (). Weekday () { Case  Time. Saturday, Time. Sunday://Multiple conditions separated by commas, matching any one can beFmt. Println ("It ' s the weekend") default:fmt. Println ("It ' s a weekday")    }//similar to the feeling of If/elseT: = Time. Now ()Switch{ CaseT.hour () < A://True to execute the following statement, false to skip directly to the default branchFmt. Println ("It ' s before noon") Case true://Continue execution, if this is false, then jump to the default branchFmt. Println ("Continue") default:fmt. Println ("It s after noon")    }

Arrays and slice are not the same thing.

The arrays in go and the arrays in C are the same concept, and the slice and Python lists are a concept, except that the slice in go must be of the same type. Arrays is a fixed length and slice is not a fixed length, you can append elements to it through the Append method, but there is no separate keyword for slice in go, which leads to the time when you don't know how to distinguish arrays from slice.

[5]int{1,2,3,4,5//这是一个数组,指明长度了slices := []int{1,2,3}      //这是一个slicemake([]int,3)    //这样也可以是一个slice

So how does slice work in go? When discussing this issue, let's take a look at some of the implementation details of the array in go, because slice is an abstraction of the array. The array in go is similar to the array in C, but there are some different places, such as the array variable for Go, which represents the entire array, rather than a pointer to the first element of the array like C, so assigning and passing an array variable in Go will result in copying all the elements in the set. The array needs to specify the length at the time of definition, or it can be used by the compiler to help us calculate the following code:

b := [...]string{"test","dwqd"}

Slice do not need to specify the length, this is the most obvious difference between the array, then what is this slice inside exactly what it is like in C + + vector? Slice is actually a wrapper and abstraction of the array, each slice inside an array, which maintains a pointer to the first element of the array, maintains the length of the array Len, and records the maximum length of the array capacity. So what's the relationship between Len and capacity? and C + + vector in the capacity one meaning it, exactly not. Confined to space here I no longer introduce the internal implementation details of slice, recommend a blog to everyone go-slice-and-internals

Wonderful experience with multiple return values

Limited to I have been writing C, often need to return multiple values, usually with the help of function parameters, the go provides the ability to return multiple values. This greatly simplifies the code and returns the error while returning the result, but remember that you can only return two values oh, don't too much.

Restricted pointers

The reason to choose to learn go is to feel that go is a Class C language, a familiar struct, a familiar pointer, but the pointer in go is limited and does not support arithmetic operations because it needs to support garbage collection. With pointers as function arguments, modifications inside the function affect the original variables, which are copied by default, and modifications within the function do not affect the original variable.

A struct like class

The struct in Go is also used to customize the data type, need to be programmed in an object-oriented way, you need to encapsulate the method and data together, C by including function pointers in the struct, go is not, the native support, directly to the struct definition method.

Package Mainimport"FMT"The type rect struct {width,height int}//gives rect a custom data type that defines two methods for Func (R *rect) area () int {return r. Width* R. Height}func (R rect) Perim () int {R. Width= -;Return2* R. Width+2*r. Height}func Main () {r: = rect{width:Ten, Height:5} FMT. Println("Area:"R. Area())//r is a value type, but the parameter type of area is a pointer ah, this can actually call FMT. Println("Perlim:"R. Perim()) FMT. Println(r) RP: = &r FMT. Println("Area:"Rp. Area()) FMT. Println("Perlim:"Rp. Perim())}

In the example above, a RECT is defined as two methods, one is a pointer as the first parameter and the other is a value as a parameter, but it can be used without distinction when used. This is actually go in the back to help us do the conversion, but does not affect the final effect, the pointer as a parameter, in the function of the internal operation will directly affect the original variable.

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.