Dive into go language-2 constants, variables, dynamic types, and static types

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

Catalogue [−]

    1. Constant
    2. Variable
    3. Variable declaration Simplification
    4. static types and dynamic types

This article describes the language details of the constants and variables of the go language.

Constant

Only numeric types and string types can be constants.

Numeric types include Boolean types, rune types, various integers, floating-point types, and complex numbers.

A constant value can be either a literal of a numeric type, a string literal, or an equivalent form of a constant, such as:

    1. Constant expressions, such as4 * 5
    2. The conversion result is a constant, such asint(10.0)
    3. The return value of the built-in function, such as,, unsafe.Sizeof caplen
    4. Applications of complex, real and imaginary numbers
    5. trueand false the constants assigned to the BOOL type
    6. Built-iniota

Assigning a variable to a constant is not allowed:

12
var "Hello World" Const //Error

The name of the constant is followed by the introduction of the previous article, and it is not surprising that you see some "strange" constant names:

12
Const π= 3.1415926const π= 3.1415926

A constant can not declare a type (untyped), it sets the default type according to the constant value, and the default type is:

    • bool
    • Rune
    • Int
    • Float64
    • complex128
    • String

In the context of a desired type, constants can be implicitly converted to the appropriate type:

123
var int = ivarfloat32 = ivarcomplex64 = i

Note that different types of variables are not convertible:

1
var float64 = v2

You cannot assign a value to a constant that cannot be implicitly converted to a constant type, for example, the following example 2147483648.0 cannot be assigned to a int32, overflow:

1
Const int32 = 2147483648.0

Go has a finite system for the underlying implementation of constants:

    • Represent integer constants with at least bits.
    • Represent floating-point constants, including the parts of a complex constant, with a mantissa of at least bits and a Signed exponent of at least.
    • Give an error if unable to represent an integer constant precisely.
    • Give an error if unable to represent a floating-point or complex constant due to overflow.
    • Round to the nearest representable constant if unable to represent a floating-point or complex constant due to limits on p Recision.

When declaring multiple variables, you can put the declaration together:

1234
Const (i = 1"Hello word")

Or put the definitions of multiple constants on one line:

1
Const I1, i2, i3 = 0, 1"Hello World"

Constants can also be defined in functions:

123
func G () {  const t = +}

Variable

A variable represents a storage location for a value, and each value has a type.

When a variable is declared with an assignment operation, the type can be omitted because it can be inferred from the value:

12
var int = var i2 = 

Similar to constant definitions, you can declare multiple variables at the same time:

1234
var (  i3 =   "Hello World")

Or one line declares multiple variables:

12
var i5, I6, i7 = "Hello World"truevarint

In the example above, i8, I9, and i10 are all int types, so the type is written on the last side, and the following notation is not allowed:

1
var int int int //Error

The following statement is also illegal because the number of variables declared and the value of the assignment list must be the same:

12
var i14, i15, i16 = +, $//Error varint =  200  //Error

Variable declaration Simplification

If a variable is initialized at the same time as it is declared, it can be simplified.
Like what

1
var i1, i2 = "Hello World"

can be simplified to

1
I1, I2: = "Hello World"

Remember, this shorthand method can only be used in functions , the variable declaration outside the function can not be abbreviated, the following writing is wrong.

123456
 Package "China" func Main () {}

Unlike a normal variable declaration, a variable declared by shorthand can "re-declare" an existing variable, as long as a new variable is guaranteed to be in the variable list, and the "re-declared" variable is of the same type as the original variable.
The following example is easy to understand:

123456
func Main () {var f *os. Filef, err: = OS. Open ("dive-into-go.pdf") fmt. Println (f, err)}

In this example f , the variable is declared again, the program compiles normally, there is no error, because it err is a new variable.
The following example compiles, because there is no new variable definition for line 4th.

1234567
func Main () {var f *os. Filevar err Errorf, err: = OS. Open ("dive-into-go.pdf") fmt. Println (f, err)}

You cannot assign a field to a struct by using the shorthand method:

12345678910
type struct {var F *os. File}func main () {var mf MyFile//var err errorMF. F, err: = OS. Open ("dive-into-go.pdf") fmt. Println (f, err)}

Note that the shorthand method sometimes confuses you because it can be shadow a variable and is compiled normally by:

1234567
x: = -func() {  x: =   //200//100

In the above example, if the intent is to modify the value of the variable x by a method of 200, the final print result may be 100, because the third line actually declares a new variable.

You can use vet the tool to check if the code contains shadow code:

1
Go Tool Vet-shadow Main8.go

The output is:

1
Main8 . Go : 8 Declaration  of x Shadows Declaration  at Main8 . Go : 6:

Variables and constants can be defined within a function or under a package, but if the variables inside the function are not used, an error is compiled, which is intentionally designed by the go language. Variables and constants under the package, the constants within the function do not have this limitation.

Reference
* Http://devs.cloudimmunity.com/gotchas-and-common-mistakes-in-go-golang/index.html#short_vars

static types and dynamic types

A static type is a declaration type when a variable is declared, in a variable declaration, when the new method creates an object, or as a type definition for an element of a struct (struct), a parameter type, and so on.

The variable of the interface (interface) type also has a dynamic type, which is the type of the specific value assigned to the variable at run time (no dynamic type when the value is nil). The dynamic type of a variable may change at run time,
This relies primarily on its assignment.

1234
var Interface {}  //x is zero value nil, static type interface{}var v *t           //V is zero value nil, static type is *tx =              
       
        //X is 42, the dynamic type is int, the static type is interface{}x = v              
        //X is (*t) (nil), the dynamic type is *t, and the static type is *t
       
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.