GO 实例

 

 

指针类型的默认值为 nil,不可以直接使用

示例代码1:

package main

import "fmt"

func main() {
    var p int
    var v *int

    // 错误用法
    //*v = p
    //fmt.Println(*v)

    v = &p
    *v = p
    fmt.Println(*v)
}

运行结果:

0

分析:

 由于 var v *int 定义得到的 v 为 nil 因此没有分配的对应内存,因此不能在 nil 地址上存储数据。

 

示例代码2:

package main

import "fmt"

func main() {
    var p int
    var v *int
    
    v = new(int)
    *v = p
    fmt.Println(*v)
}

由于 new 可以给变量分配内存,因此这种方案也能解决指针没有对应内存的问题。

 

new 和 make 的区别

 new 和 make 都是用于内存分配

 new 函数返回的类型是指针类型,new 在分配内存时会同时将对应的类型值设置为对应类型的零值,如整数的零值为 0,字符串的零值为 "",bool 的零值为 False。

 make 可以为 slice(切片),map,chan 类型分配内存,并初始化。返回值类型不是指针

 


 

 

 

自定义的新类型不会继承原类型的方法

自定义新类型的语法: type newtype  oldtype

newtype 和 oldtype 是两个完全不同的类型,newtype 不会继承 oldtype 中的方法。newtype 支持底层类型的运算,如 range, +, - 等

package main

import "fmt"

type St struct {
    Name string
}

type Student struct {
    St
}

func (St) Ping() {
    println("ping")
}

func (*St) Pong() {
    println("pong")
}

func (this *St) GetName() {
    println(this.Name)
}

type test St
type test1 Student

func main() {
    t := test{"test"}
    fmt.Printf("%v\n", t)
    //t.Ping()  //无法执行,会报错
    t1 := test1{
        St{
            Name: "test1",
        },
    }
    t1.Ping()
}

运行结果:

{test}
ping

知识点:

t.Ping()无法执行就是因为 newtype 无法继承 oldtype 的方法
t1.Ping() 能执行是因为 t1.Ping() 本质上是 t1.St.Ping()。如果针对 Student 新增了一个 func (Student) Print() { 一样是无法执行的

 

posted @ 2024-02-22 23:36  dos_hello_world  阅读(0)  评论(0)    收藏  举报