Golang Basic Syntax

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

1. When identifiers (including constants, variables, types, function names, structure fields, and so on) start with an uppercase letter, such as: Group1, an object using this form of identifier can be used by the code of the external package (the client program needs to import the package first), which is called an export (as in object-oriented languages). public), identifiers are invisible to the package if they start with lowercase letters, but they are visible and available within the entire package (like protected in object-oriented languages).

Note to distinguish whether cross-package

2.

package mainvar x, y intvar (  // 这种因式分解关键字的写法一般用于声明全局变量    a int    b bool)var c, d int = 1, 2var e, f = 123, "hello"//这种不带声明格式的只能在函数体中出现//g, h := 123, "hello"func main(){    g, h := 123, "hello"    println(x, y, a, b, c, d, e, f, g, h)}

3. Global variables are allowed to be declared but not used, local variables cannot be re-declared and declared must be used
4. Blank identifiers are also used to discard values, as values 5 are discarded in:, B = 5, 7.
_ is actually a write-only variable, you can't get its value. This is done because you have to use all the declared variables in the Go language, but sometimes you don't need to use all the return values from a function.

5. Constants can be used with Len (), Cap (), unsafe. The Sizeof () constant evaluates the value of an expression. In a constant expression, the function must be a built-in function, otherwise compiled:

package mainimport "unsafe"const (    a = "abc"    b = len(a)    c = unsafe.Sizeof(a))func main(){    println(a, b, c)}

6.iota
Iota, a special constant, can be thought of as a constant that can be modified by the compiler.
When each const keyword appears, it is reset to 0, and before the next const appears, each time a iota appears, the number it represents will automatically increase by 1.

package mainimport "fmt"func main() {    const (            a = iota   //0            b          //1            c          //2            d = "ha"   //独立值,iota += 1            e          //"ha"   iota += 1            f = 100    //iota +=1            g          //100  iota +=1            h = iota   //7,恢复计数            i          //8    )    fmt.Println(a,b,c,d,e,f,g,h,i)}

7. Pointer variable and variable address

package mainimport "fmt"func main() {    var a int = 4    var b int32    var c float32    var ptr *int    /* 运算符实例 */    fmt.Printf("第 1 行 - a 变量类型为 = %T\n", a );    fmt.Printf("第 2 行 - b 变量类型为 = %T\n", b );    fmt.Printf("第 3 行 - c 变量类型为 = %T\n", c );    /*  & 和 * 运算符实例 */    ptr = &a    /* 'ptr' 包含了 'a' 变量的地址 */    fmt.Printf("a 的值为  %d\n", a);    fmt.Printf("*ptr 为 %d\n", *ptr);    a=5    fmt.Printf("ptr 为 %d\n", ptr);//825741050416    fmt.Printf("*ptr 为 %d\n", *ptr);//5    *ptr=7    fmt.Println(*ptr,a)//7 7}

8. If do not force parentheses

package mainimport "fmt"func main() {    var a int = 100;    if a < 20 {        fmt.Printf("a 小于 20\n" );    } else if a>100{        fmt.Printf("a > 100\n" );    }else{        fmt.Printf("其他" );    }}

9.for Cycle

package mainimport "fmt"func main() {    var b int = 15    var a int    numbers := [6]int{1, 2, 3, 5}    /* for 循环 */    for a := 0; a < 10; a++ {        fmt.Printf("a 的值为: %d\n", a)    }    for a < b {        a++        fmt.Printf("a 的值为: %d\n", a)    }    //range可以对 slice、map、数组、字符串等进行迭代循环    for i,x:= range numbers {        fmt.Printf("第 %d 位 x 的值 = %d\n", i,x)    }    for{        fmt.Printf("无限循环")    }}

Goto is not recommended for

package mainimport "fmt"func main() {   /* 定义局部变量 */   var a int = 10   /* 循环 */   LOOP: for a < 20 {      if a == 15 {         /* 跳过迭代 */         a = a + 1         goto LOOP      }      fmt.Printf("a的值为 : %d\n", a)      a++        }  }

10. Function

package mainimport "fmt"func swap(x int, y string) (string, int) {    return y, x}func swap1(x , y string) (string, string) {    return y, x}func swap2(y string) string {    return y}func main() {    a, b := swap(1, "Kumar")    fmt.Println(a, b)}

11. Closures

package mainimport "fmt"func getSequence() func() int {   i:=0   return func() int {      i+=1     return i     }}func main(){   /* nextNumber 为一个函数,函数 i 为 0 */   nextNumber := getSequence()     /* 调用 nextNumber 函数,i 变量自增 1 并返回 */   fmt.Println(nextNumber())   fmt.Println(nextNumber())   fmt.Println(nextNumber())   /* 创建新的函数 nextNumber1,并查看结果 */   nextNumber1 := getSequence()     fmt.Println(nextNumber1())   fmt.Println(nextNumber1())}

12. Function method, whether it can be understood as a Java object internal method

package mainimport (   "fmt"  )/* 定义函数 */type Circle struct {  radius float64}func main() {  var c1 Circle  c1.radius = 10.00  fmt.Println("Area of Circle(c1) = ", c1.getArea())}//该 method 属于 Circle 类型对象中的方法func (c Circle) getArea() float64 {  //c.radius 即为 Circle 类型对象中的属性  return 3.14 * c.radius * c.radius}

13. Global variables, the same package can not duplicate the same name, or compile error
Pointer type variable default value is nil
14. Arrays

package mainimport "fmt"func main() {   var n [10]int /* n 是一个长度为 10 的数组 */   var i,j int   /* 为数组 n 初始化元素 */            for i = 0; i < 10; i++ {      n[i] = i + 100 /* 设置元素为 i + 100 */   }   /* 输出每个数组元素的值 */   for j = 0; j < 10; j++ {      fmt.Printf("Element[%d] = %d\n", j, n[j] )   }}

15. Emphasizing the pointer again

package mainimport "fmt"func main() {   /* 定义局部变量 */   var a int = 100   var b int= 200   fmt.Printf("交换前 a 的值 : %d\n", a )   fmt.Printf("交换前 b 的值 : %d\n", b )   /* 调用函数用于交换值   * &a 指向 a 变量的地址   * &b 指向 b 变量的地址   */   swap(&a, &b);   fmt.Printf("交换后 a 的值 : %d\n", a )   fmt.Printf("交换后 b 的值 : %d\n", b )}func swap(x *int, y *int) {   var temp int   temp = *x    /* 保存 x 地址的值 */   *x = *y      /* 将 y 赋值给 x */   *y = temp    /* 将 temp 赋值给 y */}

x = y is just a value exchange, why? Because the addresses they point to are A/b, different addresses

"Parameter Passing in Java is passed by value" means that the pass-by-value is a copy of the value passed, which is passed by reference in fact the referenced address value, so collectively, by value passing
Unlike Java, if you want to achieve the effect of reference passing, go with the pointer symbol * to
16. Structural Body

package mainimport "fmt"type Books struct {   title string   author string   subject string   book_id int}func main() {   var Book1 Books        /* Declare Book1 of type Book */   var Book2 Books        /* Declare Book2 of type Book */   /* book 1 描述 */   Book1.title = "Go 语言"   Book1.author = "www.runoob.com"   Book1.subject = "Go 语言教程"   Book1.book_id = 6495407   /* book 2 描述 */   Book2.title = "Python 教程"   Book2.author = "www.runoob.com"   Book2.subject = "Python 语言教程"   Book2.book_id = 6495700   /* 打印 Book1 信息 */   printBook(&Book1)   /* 打印 Book2 信息 */   printBook(&Book2)}func printBook( book *Books ) {   fmt.Printf( "Book title : %s\n", book.title);   fmt.Printf( "Book author : %s\n", book.author);   fmt.Printf( "Book subject : %s\n", book.subject);   fmt.Printf( "Book book_id : %d\n", book.book_id);}

17 slices
A list like Java

package mainimport "fmt"func main() {    var numbers = make([]int,3,5)    printSlice(numbers)    s :=[] int {1,2,3 }    printSlice(s)    var numbers1 []int    printSlice(numbers1)    if(numbers1== nil){        fmt.Println("切片是空的")    }    /* 打印子切片从索引1(包含) 到索引3(不包含)*/    fmt.Println("s[1:3] ==", s[1:3])    /* 默认下限为 0*/    fmt.Println("s[:3] ==", s[:3])    /* 默认上限为 len(s)*/    fmt.Println("s[2:] ==", s[2:])    numbers=append(numbers, 0,1,2,3,4,5,6)    fmt.Println(numbers,cap(numbers))    /* 创建切片 numbersc 是之前切片的两倍容量*/    numbersc := make([]int, len(numbers), (cap(numbers))*2)    /* 拷贝 numbers 的内容到 numbersc */    copy(numbersc,numbers)    fmt.Println(numbersc)}func printSlice(x []int){    fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x)//len=3 cap=5 slice=[0 0 0]}

Map

package mainimport "fmt"func main() {    var countryCapitalMap map[string]int    /* 创建集合 */    countryCapitalMap = make(map[string]int)    /* map 插入 key-value 对,各个国家对应的首都 */    countryCapitalMap["France"] = 1    countryCapitalMap["Italy"] = 2    countryCapitalMap["Japan"] = 3    countryCapitalMap["India"] = 4    delete(countryCapitalMap,"India");    /* 使用 key 输出 map 值 */    for country := range countryCapitalMap {        fmt.Println("Capital of",country,"is",countryCapitalMap[country])    }    /* 查看元素在集合中是否存在 */    captial, ok := countryCapitalMap["United States"]    /* 如果 ok 是 true, 则存在,否则不存在 */    if(ok){        fmt.Println("Capital of United States is", captial)    }else {        fmt.Println("Capital of United States is not present")    }}

19 interface

package mainimport (    "fmt")type Phone interface {    call()}type NokiaPhone struct {}func (nokiaPhone NokiaPhone) call() {    fmt.Println("I am Nokia, I can call you!")}type IPhone struct {}func (iPhone IPhone) call() {    fmt.Println("I am iPhone, I can call you!")}func main() {    var phone Phone    phone = new(NokiaPhone)    phone.call()    phone = new(IPhone)    phone.call()}

20 Exceptions

package mainimport (    "fmt"    "errors")func main() {    var err error = errors.New("this is a new error")    //由于已经实现了error接口的方法 因此可以直接调用对应的方法    fmt.Println(err.Error())}

21 The variables and methods of other files within the package are used casually, and cross-packs are passed "PackageName." Method refers to the
22 The project file must have a main package, and the main package file cannot contain duplicate main method

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.