Golang: Values, Types and Variables

2022-10-27 15:53:15 浏览数 (4)

Variables

Noted that in Go, type lies after variable/function name, which is different from all the other “C-like” languages, eg. C, C , C#, Java.

Here’s a great article on why the Go declaration syntax is the way it is (with type after names instead of before). In that article Rob Pike has already compared the Go syntax with C syntax so we won’t be doing that here. Check out the article if you are interested.

Declaration

Basic usage

代码语言:javascript复制
var foo1 int				// variable declaration
var foo2, foo3 int			// multiple variable declaration
var foo2, foo3 int = 1, 2	// ... with initializers

With implicit types

代码语言:javascript复制
var bar1, bar2 = 3.142, true    // type inferred from the right hand side
// `bar1` -> float64, `bar2` -> bool

// notice how variables with different types can be declared together this way.

Short variable declaration

Variable declaration with implicit types can be substituted for the more elegant Short variable declaration:

代码语言:javascript复制
bar3 := "hello"				// short variable declaration
// equivalent to:
var bar3 = "hello"

bar4, bar5 := true, "world"	// you can even do this

Notice that “short variable declaration” can be used multiple times for the same variable:

代码语言:javascript复制
f, err := os.Open(name)
// ...
d, err := f.Stat()

Such code is perfectly legal. However, for the second part, err is only reassigned a new value instead of being declared for a second time.

Note: This only works for variables within the same scope. if a variable with the same name is defined in an outer scope, it would create a new variable in the current scope instead of reassigning the existing outer-scope one.)

Grouped “factored” declaration (like “factored” import)

代码语言:javascript复制
var (
	foo1 uint = 12
	foo2 int = -3
	isBar bool = true
)

Types

Basic types

代码语言:javascript复制
bool

string

int  int8  int16  int32  int64
uint uint8 uint16 uint32 uint64 uintptr

byte // alias for uint8

rune // alias for int32
	 // represents a Unicode code point

float32 float64

complex64 complex128

The int, uint, and uintptr types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems. When you need an integer value you should use int unless you have a specific reason to use a sized or unsigned integer type.

Type conversion (or the lack of it)

The expression T(v) converts the value v to the type T.

代码语言:javascript复制
i := 42				// int
f := float64(i)		// float64
u := uint(f)		// uint

Unlike in C, in Go assignment between items of different type requires an explicit conversion.

This means the following code:

代码语言:javascript复制
var i int = 42
var f float32 = i	// error

should not work. Because Go doesn’t allow implicit type conversion.

Constants

Constants are declared like variables, but with the const keyword. Constants can be character, string, boolean, or numeric values. Constants cannot be declared using the := syntax.

1 人点赞