Golang basic Syntax-Basic variables (2)

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

Golang basic Syntax-Basic variables (2)

0 Value Description of the variable

    • The 0 value of a numeric type variable is0
    • The 0 value of a Boolean variable isfalse
    • The 0 value of the string type variable is"”

Type conversion syntax for variables

Variable assignments between different types in Golang require an explicit conversion

//语法格式 T(v) 将 v 转换为 类型 Tvar i int = 32var f float64 = float64(i)var u uint = uint(64)

Definition of a variable (declaration)

  • Using VAR declaration
    You can use Var to declare variables, whether inside or outside of a function

    The basic syntax format is:
    var varName varType
    var varName = Varvalue
    var varName1, VarName2 VarType
    var varName1, varName2 = varValue1, varValue2

    There are some flexible combinations in the basic syntax format, but it is not advisable to use fancy syntax

    //声明但是不初始化(foo 的值为对应变量类型的零值)var foo int;//声明且初始化(var声明初始化的时候不需要指定变量类型,编译器自动根据初始化值确定变量类型)var bar  = 3 //推荐写法var bar int = 3 //合法但是不推荐//声明 i1, i2 为 int 类型(初始值为 int 类型的零值 0)var i1, i2 int//声明 i1 和 i2同时赋值为1,2var i1, i2 = 1, 2//声明 int 类型的 i1,string 类型的 s1var i1, s1 = 1, "a"//声明一组全局变量,变量可以初始化或者不初始化var(    i1, i2 = 1, 2    i3, i4 int    s1 = "111221"    b1 = true)
  • Quick syntax
    You can only use the shortcut syntax in the function body, the function is illegal outside

    Syntax format
    VarName1: = varValue1

    func main(){    //声明变量 i1并且同时给变量赋值    i1 := 1    //声明变量 i2,s1并且同时给他们赋值    i2, s1 := 1, "11"}
  • The Var declaration and the shortcut syntax declaration need to be noted

    A convenient declaration method is to declare a new variable and assign a value, and cannot be used as a variable assignment to a var declaration

    var foo = 1func main(){    foo := 10    //输出10 使用的局部变量取值    fmt.Println(foo)    //PS: 一定要注意下面有语法错误    var bar int    bar := 11   //便捷方式其实是先声明一个新变量然后给赋值,但是此时 bar 变量已经存在了不能重复定义}

Special variables_

Variable is _ used to discard ignoring a value, no unused variable is allowed in Golang

    • function multiple return value discard

      _, r := divide(10, 3)
    • The import package is not used (but the Init method that imports the package is called)

      import(    "fmt"    _ "os")

Constant

A constant is a variable that, once defined, is determined by its value at compile-time and cannot be changed at runtime, and the number|boolean|string type in Golang can be defined as a constant

Definition syntax
Const CONSTANTNAME = value
cosnt Constantname Constanttype = value

const PI = 3.14const Pi float32 = 3.14156

Variable type

The basic variable types in Golang are mainly number,bool,string, etc.

Boolean

Keywords are bool used to define a Boolean variable, and the value of a Boolean variable is only true and false 0 values (the default value) arefalse
Golang does not allow the conversion of a Boolean type to a numeric type

Number Type (numerrical)

Integers

Golang does not allow the operation of variables of different types, such as variables of type int8 and variables of type int32, cannot be additive

    • Signed

      • The int length depends on the operating system, 32-bit operating system is 32-bit, 64-bit operating system is 64-bit
      • Rune It's Int32 's nickname.
      • int8
      • Int16
      • Int32
      • Int64
    • Unsigned

      • UInt
      • Byte it is an alias of uint8
      • Uint8
      • UInt16
      • UInt32
      • UInt64

Floating point Type

Note that there is no float for this type

    • Float32
    • Float64

Plural (Complex)

    • complex128
    • Complex64

Strings (String)

GOALNG uses UTF-8 as a combination of encodings, using "or" the wrapped character is a string
' Define multi-line strings

var s1 = "hello"var s2 = `helloword`

The string object does not allow the value to be changed (but can be re-assigned), the following syntax error

var s = "hello"s[0] = 'c'

If you want to change the value of a variable, you need to use the old variable to create

s := "heloo"c := byte(s) //string 转换为[]byte 类型c[0] = 'c's2 := string(c) //把 c []byte 转为 stringfmt.Printf("%s\s\n", s2)

+can be used to stitch two strings

s := "hello, "m := "world"a := s + mfmt.Printf("%s\n", a)//输出 "cello, "s = "c" + s[1:] //返回 "c" + s从索引1到结束的字符串拼接

Error (Golang built-in, not in other languages)

Golang No try-catch statement block handling exception with built-in error type for handling errors

err := errors.New("some error messaage")if err != nil {    //TODO something}

Other

    • Grouping definitions
      If you want to define multiple constants, variables or import multiple packages, you can use the grouping format

      //以下是非分组形式import "fmt"import "os"const i = 100const pi = 3.145var i intvar pi float32var prefix string//分组形式import(    "fmt"    "os")const(      pi = 3.145    prefix = "GO")var(    pi float32    prefix string)
    • Iota Enumeration

      The keyword Iota can generate an enumeration type, with an enumeration value starting at 0 and adding 1 each time

const(        //x == 0        x = iota        //y == 1        y = iota         //z == 2        z = iota         //如果常量名称后面没有任何表达式        //则 w 等价于 w = iota, w == 3        w    )    const v = iota //v == 0    //PS 注意在同一行时的 iota 特殊情况    const(        //如果 iota 在同一行,则 e == f == g == 0        e, f, g = iota, iota, iota     )
    • The visibility of variables

      • Any variable that starts with a capital letter can be exported, which can be accessed outside the package,
      • Functions or constant capital letters, which can be exported, can be accessed outside the package.
      • There is no public or private in Golang to control the visibility of variable function constants, such as the name of the variable function constant, whether the first letter is case-insensitive to determine
package test//Foo 在包 test 之外可以通过 test.Foo 访问var Foo//bar 在包 test 之外通过 test.bar 访问是错误的,因为它的首字母是小写,包外不可见var bar//函数在test 包外可以使用 test.Test1()访问func Test1(){}//函数在 test 包外不可以通过 test.test2()访问,只可以在包内使用func test2(){}//包外使用 test.I访问Const I = 1// j 不可以在包外通过 test.j 访问cont j = 10

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.