Go basic series (7): constants and variables

Source: Internet
Author: User
Tags uppercase letter
Constants (constants) and iota

A constant contains data that will not be changed. The data type of a constant can only be boolean, number (INT/float/complex), or string.

Definition method:

const NAME [TYPE] = VALUE

Type can be omitted, because constants are simple data types, and the compiler can deduce their data types based on their values.

For example:

const Pi = 3.14159

Constants are evaluated during compilation, so the defined constants must be computed during compilation.. For example, it is wrong to call some functions during the runtime to generate the constant value, because these functions cannot be called during compilation.After the constant value is defined, it cannot be changed during running.Otherwise, an error is reported.

Const c = 3 + 2 // correct const d = getnumber () // Error

The accuracy of constants can be long at will, so go will not experience the problem of precision overflow. If the value of a constant value is too long, you can use the line feed.\:

const Ln2= 0.693147180559945309417232121458            176568075500134360255254120680009const Log2E= 1/Ln2const Billion = 1e9

In go, overflow occurs only when values that exceed the accuracy of the variable are assigned to the variable.

You can define multiple constants at a time:

const beef, two, c = "meat", 2, "veg"const Monday, Tuesday, Wednesday = 1, 2, 3const (    Monday, Tuesday, Wednesday = 1, 2, 3    Thursday, Friday, Saturday = 4, 5, 6)

Constants can be enumerated. After the following constants are defined, female represents the value 1.

const (    Unknown = 0    Female = 1    Male = 2)

AvailableiotaImplement enumeration,iotaIt is a constant defined in the builtin package and its value is 0. It is used to define the number of sequences in the constant and increases from 0:

const (    a = iota    b = iota    c = iota)

WheniotaWhen the first call is made, a value of 0 is generated. When iota is called again in the new line, it is automatically increased by 1.a=0,b=1,c=2. The above constant enumeration can be abbreviated to the equivalent form:

const (    a = iota    b    c)

Iota cannot be used during running because it is a constant starting with a lowercase letter and will not be exported. The following code returns an error: iota is not defined.

var a int = iota

iotaIt can also be used in expressions, suchiota+50Adds 50 to the current iota value.

The value of iota is reset and initialized for each const block structure..

func main() {    const a = iota           // a=0    const b = iota + 3       // b=3    const c,d = iota,iota+3  // c=0,d=3    const (        e = iota           // e=0        f = iota + 4       // f=5        g                  // g=6    )    println(a,b,c,d,e,f,g)}
Variable

Before using variables, there are two processes: declaring variables and assigning values to variables. Declared variables are also known as "definition variables ". It must be used after variable Declaration; otherwise, an error is reported.

Common Methods for defining variables:

var identifier type

For example:

VaR A intvar B boolvar STR string // or var (A int B bool STR string)

When the variable is declared, the default 0 Initialization is performed. The default 0 initialization value for each data type is different. For example, if the 0 value of the int type is 0, the 0 value of float is 0.0, the 0 value of the string type is null "", and the 0 value of the bool type is false, the value 0 of the data structure is nil, and the value 0 of struct is null.

The value of a variable can be obtained during compilation. However, if the value assigned to a variable needs to be calculated during running, the value can be obtained only after running.

VaR A Int = 15 // assign a value during compilation var B INT = 15/3 // assign a value during compilation var c = getnumber () // assign a value during runtime

Declarations and assignments can be combined:

var a int = 15var i = 5var b bool = falsevar str string = "Hello World"

When the Declaration and value assignment are combined, the type part can be omitted for the value of the simple data type, because go can deduce the type based on the value itself:

var a = 15var b = falsevar str = "Hello World"var (    a = 15    b = false    str = "Hello World"    numShips = 50    city string)

To deduce the data type, the type inference operation is completed during running.

If you want to specify a specific type when you use an inferred type value, you must explicitly specify it. For example, if the type of an integer is int, you must explicitly specify the type to save it to int64:

var a int64 = 2

The type to be inferred must be declaration and value assignment. Otherwise, there is no value and it cannot be inferred based on the value. For examplevar aYes.

In addition to the above inference method:=The symbol can also realize the combination of declaration and value assignment. It will also be inferred based on the data type, even if the VaR keyword is omitted:

a := 50

It should be noted that the variable cannot be declared again after it is declared (unless it is in different scopes) and can only be used later=Assign values. For example, an error is returned when you execute the following code:

package mainimport ("fmt")func main(){    x:=10    fmt.Println("x =",x)    x:=11    fmt.Println("x =",x)}

The error is as follows:

# command-line-arguments.\test.go:8:3: no new variables on left side of :=

The error message is obvious,:=There are no new variables on the left.

If you carefully read the error message above, you will findno new variablesIs a plural number. Actually, go allows us to use:=One-time declaration and assignment of multiple variables, as long as there is anyOneThe syntax is correct for new variables.

Func main () {name, age: = "longshuai", 23 FMT. println ("name:", name, "Age:", age) // rename a value because there is a new variable weight, name: = 90, "malongshuai" FMT. println ("name:", name, "Weight:", weight )}

Note that the name is:=Assign value. After go first deduced the Data Type of the variable, it is not allowed.:=Then change its data type, because only for the first time:=Declare the name, and then all:=Name is a simple assignment operation.

For example, the following error is reported:

weight,name := 90,80

Error message:

.\test.go:11:14: cannot use 80 (type int) as type string in assignment

In addition, variables must be used after declaration; otherwise, an error is reported because go has strict requirements on the specifications. For exampleweightBut it is not used:

weight,name := 90,"malongshuai"fmt.Println("name:",name)

Error message:

.\test.go:11:2: weight declared and not used
Scope)
  • The variable defined in the function is a local variable, which is only visible in the function.
  • Defined in a code block (for example{...CODE...}) Is also a local variable, except for the code block.
  • Variables defined outside the code block and outside the function are package variables or global variables, they can be accessed by multiple files in the same package under the same directory (because one directory in go can only define one package, but one package can be divided into multiple files)
    • If the variable name starts with a lowercase letter, other packages cannot access the variable.
    • If the variable name starts with an uppercase letter, other packages can access the variable.

Variable names of different scopes can conflict, but we recommend that you name variables in a unique way.

Go basic series (7): constants and variables

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.