drmet46444 2016-05-11 18:20
浏览 9
已采纳

带父结构嵌入父结构的调用函数不起作用

A bit confused on this one. Please see playground.

I would expect go to allow you to call a method that takes a parent with a child that embeds that parent.

 package main

import (
    "fmt"
)

type Parent struct {
    A string
}

type Child struct {
    Parent 
}

func SomeFunction(parent Parent) {
    fmt.Println("%v", parent.A)
}

func main() {
    child := Child{Parent{A:"test"}}
    SomeFunction(child)  //prog.go:21: cannot use child (type Child) as type Parent in argument to SomeFunction
}

If I call this with "child.Parent" it works but in that case I can't use any code within the function that utilizes the value as an empty interface. Googled the heck out of this and found one very interesting and helpful page. Golang concepts from an OOP point of view. Any guidance on what i'm missing here is welcome. Perhaps this is just me not fully "getting" Golang here.

  • 写回答

1条回答 默认 最新

  • duangaixing1509 2016-05-11 18:34
    关注

    Golang does not support inheritance, so the concept of parents and children do not exist. This makes the names confusing in the text below. It also indicates that you need to make the mental leap between reimplementing inheritance, to designing data structures in a go-like manner. This very issue took me some time to get my head around, and the answer was 'don't start with an inheritance hierarchy and wonder how to do it in go, start with go and design what you want to do with the tools available'.

    SomeFunction is defined to take a Parent as a parameter, so you must pass it a parent. If you want to pass it a child, you need to do this, i.e. use:

    SomeFunction(child.Parent)
    

    That's what you do to pass an embedded struct.

    However, what I suspect you really want to do is declare an interface called Parent, have Child implement it, and have SomeFunction take a Parent interface. Your confusion is then going to be that currently Parent has a data member, and interfaces have only functions. The neatest way to fix that depends on what you are trying to do, but one route would be to provide another function to return the data member. All the 'child' classes could then embed this data member and a the function could return it (or a pointer to it). However, without a clearer idea of what you are trying to do, this is only speculation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用