使用Golang中的方法进行结构转换

In order to simplify imports and dependencies for a project, I would like to convert a type struct and still have access to all the methods it is attached to.

This is what I am looking for :

type foo struct {
a int
}

func (f *foo) bar() {
    f.a = 42
}

type foo2 foo

func main() {
    f := foo{12}
    f.bar()
    f2 := foo2(f)
    f2.a = 0
    f2.bar()
    fmt.Println(f)
    fmt.Println(f2)
}

On the line "f2.Bar()" I get the error :

"f2.Bar undefined (type Foo2 has no field or method Bar)"

How can I do to have access to the method Bar even if I made a conversion. I would like my output to be

{42}
{42}

You can use struct embeding

package main

import (
    "fmt"
)

type foo struct {
    a int
}

func (f *foo) bar() {
    f.a = 42
}

type foo2 struct {
    foo
}

func main() {
    f := foo{12}
    f.bar()
    f2 := foo2{}
    f2.a = 0
    f2.bar()
    fmt.Println(f)
    fmt.Println(f2)
}

Just create struct and use foo as one of its members. Don't give it explicit name

type foo2 struct {
    foo
}

That way all methods of foo will be available for foo2.

Note that output of this program will be:

{42}
{{42}}

More effective way of achieving what I suppose you want to do, will come with new Go 1.9: https://tip.golang.org/doc/go1.9#language