golang new

作者: 时间: 2023-02-01 评论: 暂无评论

在 golang 中 new 是另外一种创建变量的方式。通过 new(T) 可以创建 T 类型的变量(这里 T 表示类型),初始值为 T 类型的 零值返回值为其地址 (地址类型是 *T)。

package main

import "fmt"

func newInt1() *int {

return new(int)

}

func newInt2() *int {

var a int
return &a

}

func main() {

p := newInt1()
q := newInt2()
fmt.Println(p, q) // 0xc00001c0b8 0xc00001c0c0

}

go的切片

作者: 时间: 2022-05-29 评论: 暂无评论

1.看一段代码
func main() {

    s1 := [5]int{0, 1, 2, 3, 4}
    s2 := s1
    s2[0] = 999
    fmt.Println(s1)   //[0 1 2 3 4]

    s3 := []int{0, 1, 2, 3, 4}
    s4 := s3
    s4[0] = 999    //[999 1 2 3 4]   s3数组是值类型,s3 切片本身是个引用类型
    fmt.Println(s3)
}