Go - Proverb: Accept interfaces, return structs

发布时间 2023-09-19 11:22:50作者: ZhangZhihuiAAA

fake.go

package fake

import "fmt"

type ExampleStruct struct {
    Item1 string
    Item2 string
    Item3 string
}

func (e ExampleStruct) LogLine() {
    fmt.Printf("%+v\n", e)
}

 

main.go

package main

import (
    "github.com/xxx/fake"
)

func main() {
    a := fake.ExampleStruct{Item1: "a"}
    PrintExample(a)
}
func PrintExample(e fake.ExampleStruct) {
    e.LogLine()
}

 

new_main.go

package main

import (
    "github.com/xxx/fake"
)

func main() {
    a := fake.ExampleStruct{Item1: "a"}
    PrintExample(a)
}

type ExampleInterface interface {
    LogLine()
}

func PrintExample(e ExampleInterface) {
    e.LogLine()
}

 

anotherfake.go

package anotherfake

import "fmt"

type ExampleStruct struct{}

func (e ExampleStruct) LogLine() {
    fmt.Printf("This is from anotherfake package :: %+v\n", e)
}

 

new_main_4_anotherfake.go

package main

import (
    "github.com/xxx/anotherfake"
)

func main() {
    a := anotherfake.ExampleStruct{}
    PrintExample(a)
}

type ExampleInterface interface {
    LogLine()
}

func PrintExample(e ExampleInterface) {
    e.LogLine()
}

 

Notice that in the modified main Golang module, the only that is being altered is the struct that is being defined and instantiated to be passed to the rest of the code in the module. Other than that, there is little or no other change that is kind of required.