go - 类型、接口(interface)和指针

标签 go

我有一个简单的代码:

type Namer interface {
    PrintName()
}

type P struct {
    Name string
}

func (p *P) PrintName() {
    fmt.Printf("%s\n", p.Name)
}

func main() {
    p := P{Name: "Name"}

    var namers []Namer
    namers = append(namers, &p)
    fmt.Println(reflect.TypeOf(namers[0]))

    on := &namers[0]
    fmt.Println(reflect.TypeOf(on))
    (*on).PrintName()
    (**on).Name = "EEEE"
    (*on).PrintName()
}

还有一堆问题:)

  1. 为什么我不能写:append(namers, p)? &p 是指向 P 的指针,array namers 不是指针数组
  2. 为什么 TypeOf(namers[0]) 是 *P 而 TypeOf(on) 是 *Namer?没意义,TypeOf(&(*P)) 应该是**P
  3. 为什么最后一行打印:“Name”而不是“EEE”?

感谢您的帮助!

最佳答案

断言 *on*P 类型。例如,

package main

import (
    "fmt"
    "reflect"
)

type Namer interface {
    PrintName()
}

type P struct {
    Name string
}

func (p *P) PrintName() {
    fmt.Printf("%s\n", p.Name)
}

func main() {
    p := P{Name: "Name"}

    var namers []Namer
    namers = append(namers, &p)
    fmt.Println(reflect.TypeOf(namers[0]))

    on := &namers[0]
    fmt.Println(reflect.TypeOf(on))
    (*on).PrintName()
    (*on).(*P).Name = "EEEE"
    (*on).PrintName()
}

输出:

*main.P
*main.Namer
Name
EEEE

关于go - 类型、接口(interface)和指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30139200/

相关文章:

encryption - golang rsa解密没有填充?

go - 发生http超时时,如何获取json.NewDecoder(body).Decode()的错误原因?

go - 是否可以扩展 go struct 构造函数?

go - 编写具有多个可选参数的 API 端点

google-app-engine - Go - AppEngine - 性能

go - 使用 openwire 协议(protocol)连接事件的 mq

json - JSON 编码器/解码器的不同结构属性 "published"

go - 库/pq : Runtime error when querying a database

mongodb - Golang mgo 获取空对象

postgresql - 使用数组去 postgres `SELECT * IN`