首次提交:初始化项目代码

This commit is contained in:
sunct
2026-07-31 15:18:32 +08:00
commit d6393266b0
193 changed files with 14287 additions and 0 deletions
+41
View File
@@ -0,0 +1,41 @@
package main
import "fmt"
func main() {
// 基本类型转换
var a int = 10
var b float64 = float64(a) // 安全转换
var c int = int(b + 0.9) // 丢失精度,c=10
fmt.Printf("a=%d, b=%.1f, c=%d\n", a, b, c) // 输出a=10, b=10.0, c=10
// 字符串与字节/符文切片转换
s := "中文"
bytes := []byte(s) // 转为字节切片(UTF-8编码,"中"占3字节)
runes := []rune(s) // 转为符文切片(每个字符对应一个rune)
fmt.Printf("s bytes: %x, s runes: %c\n", bytes, runes) // 输出s bytes: e4b8ade69687, s runes: [中 文]
// 数组转切片
arr := [3]int{1, 2, 3}
slice := arr[:]
fmt.Println("数组转切片:", slice) // 输出数组转切片: [1 2 3]
// 接口类型断言(多值形式)
var i interface{} = "hello"
if str, ok := i.(string); ok {
fmt.Printf("i is string: %s\n", str) // 输出i is string: hello
} else if num, ok := i.(int); ok {
fmt.Printf("i is int: %d\n", num)
} else {
fmt.Println("i is unknown type")
}
// 接口类型断言(单值形式,需确保类型正确)
var j interface{} = 100
num := j.(int)
fmt.Printf("j is int: %d\n", num) // 输出j is int: 100
// 错误示例(断言失败)
str := j.(string) // 报错:panic: interface conversion: interface {} is int, not string
fmt.Println(str)
}