2016-05-13 28 views
0

我想在golang中實現繼承。 下面是例子:使用golang中的繼承方法訪問對象

type A struct { 
    Number int 
} 

type B struct{ 
    A 
    name String 
} 

func (a A) GetNumber() { 
    // Here I want to use instance of B 
    fmt.Println(a) // but this is giving me instance of A 
} 

是否有可能在A的函數來獲得B的情況下,如果A正在被B繼承?

+2

Go中沒有繼承。一些相關/可能的重複:[one](http://stackoverflow.com/questions/21251242/is-it-possible-to-call-overridden-method-from-parent-struct-in-golang),[two] (http://stackoverflow.com/questions/30622605/can-embedded-struct-method-have-knowledge-of-parent-child),[三](http://stackoverflow.com/questions/29390736/go- embedded-struct-call-child-method-instead-parent-method),[four](http://stackoverflow.com/questions/29144622/what-is-the-idiomatic-way-in-go-to-create -的-結構-a複雜的層次結構)。 – icza

回答

1

首先,你的代碼有錯誤。在您尚未創建另一個類型爲String之前,您必須將其更正爲string

然後在Go中,您可以使用複合結構,這意味着您可以直接訪問另一個結構中包含的結構字段,就像您已經這樣做了。

這意味着你可以在一個方法接收器上調用一個方法,該方法接收器的struct域聲明。要糾正你的例子,如果我理解正確的話你的問題:

package main 

import (
    "fmt" 
) 

type A struct { 
    Number int 
} 

type B struct{ 
    A 
    name string 
} 

func main() { 
    b := &B{A{1}, "George"} 
    b.GetValues() 
} 

func (b B) GetValues() {  
    fmt.Println(b.Number) 
    fmt.Println(b.name) 
} 

在下面的例子中,因爲struct A包括在struct B這意味着你可以調用在GetValues方法struct A聲明的結構域。這是因爲struct B繼承struct A字段。

https://play.golang.org/p/B-XJc6jddE