Administrator
发布于 2023-03-06 / 46 阅读
0
0

Golang--Primitive Types and Declarations

string variable & string literals

package main

import "fmt"

func main() {
	var name string = "zhangsan"
	fmt.Println(name)
}

var name string = "zhangsan",这行代码中,等号左边的,是string variable;等号右边的,是string literals

注意区分string variable & string literals 对应的概念

Automatic Type Promotion & Explicit Type Conversion

Go doesn’t allow automatic type promotion between variables. You must use a type conversion when variable types do not match.

Even different-sized integers and floats must be converted to the same type in order to interact.

var x int = 10
var y float64 = 30.2
var z float64 = float64(x) + y
var d int = x + int(y)

How understand Const Keyword

Constants in Go are a way to give names to literals.

There is no way in Go to declare that a variable is immutable.

They can only hold values that the compiler can figure out at compile-time.

const x int64 = 10

const (
	idKey   = "id"
	nameKey = "name"
)
const z = 20 * 10

func main() {
	const y = "hello"
	fmt.Println(x)
	fmt.Println(y)
}


评论