3. 变量
3.1 定义变量
package main
import "fmt"
var flg bool
func main() {
var name int = 1
fmt.Println(name)
age := 1
fmt.Println(age)
var s1, s2 = "s1", 2
s1 = "s2"
fmt.Println(s1, s2)
var (
s3 = "s3"
s4 int = 4
s5 bool
)
fmt.Println(s3, s4, s5)
}
3.2 常量
package main
import "fmt"
func main() {
const PI float32 = 3.14
const (
x int = 16
y
s = "abc"
z
)
fmt.Println(x, y, s, z)
}
3.3 iota
package main
import "fmt"
func main() {
const (
err1 = iota
err2 = iota
err3 = iota
)
fmt.Println(err1, err2, err3)
const (
e1 = iota
e2
e3 = 100
e4
e5 = iota
e6
)
fmt.Println(e1, e2, e3, e4, e5, e6)
}
3.4 匿名变量
package main
import "fmt"
func a() (int, bool) {
return 0, false
}
func main() {
var _ int
r1, _ := a()
fmt.Println(r1)
}
4. 数据类型
4.3 类型转换
package main
import (
"fmt"
"strconv"
)
func main() {
var strint = "12"
myint, err := strconv.Atoi(strint)
if err != nil {
fmt.Println("convert error")
}
fmt.Println(myint)
fmt.Println(strconv.Atoi(strint))
var intstr = 32
fmt.Println(strconv.Itoa(intstr))
myfloat, err := strconv.ParseFloat("3.14", 64)
if err != nil {
fmt.Println("convert error")
}
fmt.Println(myfloat)
myint2, err := strconv.ParseInt("-42", 10, 64)
if err != nil {
fmt.Println("convert error")
}
fmt.Println(myint2)
mybool, err := strconv.ParseBool("0")
if err != nil {
fmt.Println("convert error")
}
fmt.Println(mybool)
boolstr := strconv.FormatBool(true)
fmt.Println(boolstr)
floatstr := strconv.FormatFloat(3.1415, 'E', -1, 64)
fmt.Println(floatstr)
fmt.Println(strconv.FormatInt(-42, 16))
}
5. 字符串操作
5.4 输出
package main
import (
"fmt"
"strings"
)
func main() {
name := "neo"
msg := fmt.Sprintf("用户:%s", name)
fmt.Println(msg)
var builder strings.Builder
builder.WriteString("你好")
builder.WriteString(name)
re := builder.String()
fmt.Println(re)
}
5.6 字符串函数
package main
import (
"fmt"
"strings"
)
func main() {
name := ",.hello,go."
fmt.Println(strings.Contains(name, "go"))
fmt.Println(strings.HasPrefix(name, "hello"))
fmt.Println(strings.HasSuffix(name, "go"))
fmt.Println(strings.Count(name, "o"))
fmt.Println(strings.Index(name, "he"))
fmt.Println(strings.Split(name, ","))
fmt.Println(strings.Trim(name, ",."))
fmt.Println(strings.Replace(name, "go", "java", 2))
}
6. 条件控制
package main
import "fmt"
func main() {
for i := 0; i < 3; i++ {
fmt.Println(i)
}
name := "immocgo"
for index, value := range name {
fmt.Println(index, value)
}
age := 16
if age < 18 {
fmt.Println("child")
} else if age == 18 {
fmt.Println("18")
} else {
fmt.Println("adult")
}
switch age {
case 18:
fmt.Println("18")
case 17, 16:
fmt.Println("17,16")
default:
fmt.Println("default")
}
switch {
case age == 18:
fmt.Println("18")
case age < 18:
fmt.Println("child")
default:
fmt.Println("default")
}
}