声明:
var 变量
const 常量
type 类型
func 函数实体
var name (type)/(= …)
int型 初始值 0
bool型初始值 false
字符串型初始值 “”
接口或者引用类型(slice map chan function)初始值为nil
可以连续声明
包级别 变量在main入口执行前完成初始化,局部变量在执行到时候初始化
// Package tempconv performs Celsius and Fahrenheit temperature computations.
package tempconv
import "fmt"
type Celsius float64 // 摄氏温度
type Fahrenheit float64 // 华氏温度
const (
AbsoluteZeroC Celsius = -273.15 // 绝对零度
FreezingC Celsius = 0 // 结冰点温度
BoilingC Celsius = 100 // 沸水温度
)
func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }
func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }
A(B b) 将B转型为A 但是值不变(仍然是底层float 64的数据)
type 定义新的类型 type A float64表示A是64位浮点数据
不同类型间无法比较
func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }
func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) }
函数名之前 参数表示 定义了一个String当打
函数名之后表示正常的传参
作用域:
对字符进行大小写转换:
strings.ToUpper("Gopher")
//调用方法
x := x + 'A' - 'a'
//每一个字符使用该操作进行大写化,输入必须是小写
//分块循环
func main() {
x := "hello!"
for i := 0; i < len(x); i++ {
x := x[i]
if x != '!' {
x := x + 'A' - 'a'
fmt.Printf("%c", x) // "HELLO" (one letter per iteration)
}
}
}
//变量的重复使用(不同作用域)
func main() {
x := "hello"
for _, x := range x {
x := x + 'A' - 'a'
fmt.Printf("%c", x) // "HELLO" (one letter per iteration)
}
}
//注意作用域范围???还没太懂
var cwd string
func init() {
cwd, err := os.Getwd() // NOTE: wrong!
if err != nil {
log.Fatalf("os.Getwd failed: %v", err)
}
log.Printf("Working directory = %s", cwd)
}