前往:将同一个名称和内容结构放在一个包中,然后将其初始化

There is a package named mount, which has two same name and content structs

mount_linxu.go

package mount
import "fmt"
type Mounter struct {
}
func (mounter *Mounter) DoMount(path string) (bool ,error){
fmt.Printf("this is linux")
return true , nil
}

mount_mac.go

package mount
import "fmt"
type Mounter struct {
}
func (mounter *Mounter) DoMount(path string) (bool ,error){
fmt.Printf("this is mac")
return true , nil
}

mount_test.go

func TestNew(t *testing.T) {
 mounter := New()
 mounter.DoMount("")
}

My Question is why Mounter in mount_mac.go will be initialised always?

As presented, those files won't compile since you are declaring Mounter two times within the same package.

Your options to make this work are:

1) Use two different packages for each of those files, like:

/src/components/mac/mount_mac.go

/src/components/linux/mount_linux.go

Then, import the package you need in each case.

2) Use conditional build so that depending on the platform you are targeting, only one of the files is included. You can use a // +build tag in each file.

See more about that here: https://golang.org/pkg/go/build/#hdr-Build_Constraints

If you use the correct file suffixes, they will be conditionally built based on OS. Go does not refer to MacOS as "mac", it refers to it as "darwin" (the Mac kernel). It also correctly spells "linux", though I don't know if that was just typo'd in the question or if your file name on disk has the same typo. Alternatively, you can use explicit build constraints rather than file names, but the file names are idiomatic for OS- or architecture-specific code.

If the struct definitions are identical, you can put the struct in a general mount.go file, and just put the OS-specific method definitions in the OS-specific files to avoid unnecessary duplicate code.