Files
bulma/new_demo.go
T

46 lines
1.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import "fmt"
// 示例结构体
type NewUser struct {
Name string
Age int
}
func main() {
// 1. 基本类型
intPtr := new(int)
fmt.Printf("intnew):值=%d,类型=%T\n", *intPtr, intPtr) // 输出:值=0,类型=*int
// 2. 结构体
userPtr := new(NewUser)
fmt.Printf("NewUsernew):%+v,类型=%T\n", *userPtr, userPtr) // 输出:{Name: Age:0},类型=*main.NewUser(注:Go语言中的类型在反射或格式化输出时会显示完整的包路径)
// 3. 数组
arrPtr := new([2]string)
(*arrPtr)[0] = "golang"
fmt.Printf("数组(new):%v,类型=%T\n", *arrPtr, arrPtr) // 输出:[golang ],类型*[2]string
// 4. 切片(需配合make初始化内部结构)
slicePtr := new([]int)
// *slicePtr = make([]int, 2) // 初始化内部结构
(*slicePtr)[0] = 100
fmt.Printf("切片(new):%v,类型=%T\n", *slicePtr, slicePtr) // 输出:[100 0],类型=*[]int
// 5. map(需配合make初始化)
mapPtr := new(map[int]string)
*mapPtr = make(map[int]string)
(*mapPtr)[1] = "one"
fmt.Printf("mapnew):%v,类型=%T\n", *mapPtr, mapPtr) // 输出:map[1:one],类型=*map[int]string
// 6. 与&的对比(结构体自定义初始化)
customUser := &NewUser{Name: "Alice", Age: 25}
fmt.Printf("NewUser&):%+v,类型=%T\n", *customUser, customUser) // 输出:{Name:Alice Age:25},类型=*main.NewUser
// 7. 与make的对比(切片直接使用)
makeSlice := make([]int, 2)
makeSlice[0] = 200
fmt.Printf("切片(make):%v,类型=%T\n", makeSlice, makeSlice) // 输出:[200 0],类型=[]int
}