变量 Varaible
基本变量类型
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
声明
变量声明方式
正常声明
var smsSendingLimit int
smsSendingLimit = 60
var costPerSMS float64 = 0.2
var hasPermission bool
var username string
快速声明
smsSendingLimit := 60
penniesPerText := 2.0
averageOpenRate, displayMessage := .23, "is the average open rate of your messages"
常量 Constant
常量不能够做任何修改和重新赋值,常量计算是在编译过程中完成。
func calculateTime() {
const secondsInMinute = 60
const minutesInHour = 60
const secondsInHour = minutesInHour * secondsInMinute
fmt.Println("number of seconds in an hour:", secondsInHour)
}
格式化字符显示
格式化字符显示不太好用,不太优雅。
- fmt.Printf - Prints a formatted string to standard out.
- fmt.Sprintf() - Returns the formatted string
func createUser(firstName, lastName string, age int) {
fmt.Printf("My name is %s %s, I'm %d years old\n", firstName, lastName, age)
var returnOfSprintf string = fmt.Sprintf("My name is %s %s, I'm %d years old\n", firstName, lastName, age)
fmt.Println(returnOfSprintf)
}
%v
- Interpolate the default representation
fmt.Printf("I am %v years old\n", 10)
// I am 10 years old
fmt.Printf("I am %v years old\n", "way too many")
// I am way to many years old
%s
- Interpolate a string
fmt.Printf("I am %s years old\n", "way too many")
// I am way to many years old
%d
- Interpolate an integer in decimal integer form
fmt.Printf("I am %d years old\n", 10)
// I am 10 years old
%f
- Interpolate a decimal float
fmt.Printf("I am %f years old\n", 10.523)
// I am 10.523000 years old
fmt.Printf("I am %.2f years old\n", 10.523)
// I am 10.52 years old