I have the following code:
package main
import (
"log"
)
type Data struct {
Id int
Name string
}
type DataError struct {
Message string
ErrorCode string
}
func main() {
response := Data{Id: 100, Name: `Name`}
if true {
response = DataError{Message: `message`, ErrorCode: `code`}
}
log.Println(response)
}
This code returns me an error:
./start.go:20: cannot use DataError literal (type DataError) as type
Data in assignment
Seems to be that I could not assign to response var data with different type (in my case DataError). I heard that possible solution could be to unite Data and DataError structs via interface. Or maybe there is another better solution?
Could you please point me how to resolve this problem?
Thanks
It looks like you're trying to make a union type (what the ML-family of languages calls "enum"). I know of a couple of patterns for this:
0. Basic error handling (playground)
I suspect what you're doing is just basic error handling. In Go, we use multiple return values and check the result. This is almost certainly what you want to do:
package main
import (
"fmt"
"log"
)
type Data struct {
ID int
Name string
}
type DataError struct {
Message string
ErrorCode string
}
// Implement the `error` interface. `error` is an interface with
// a single `Error() string` method
func (err DataError) Error() string {
return fmt.Sprintf("%s: %s", err.ErrorCode, err.Message)
}
func SomeFunction(returnData bool) (Data, error) {
if returnData {
return Data{ID: 42, Name: "Answer"}, nil
}
return Data{}, DataError{
Message: "A thing happened",
ErrorCode: "Oops!",
}
}
func main() {
// this bool argument controls whether or not an error is returned
data, err := SomeFunction(false)
if err != nil {
log.Fatalln(err)
}
fmt.Println(data)
}
1. Interfaces (playground)
Again, if your options are good-data and error, you should probably use the first case (stick with the idiom/convention), but other times you might have multiple "good data" options. We can use interfaces to solve this problem. Here we're adding a dummy method to tell the compiler to constrain the possible types that can implement this interface to those that have an IsResult() method. The biggest downside to this is that sticking things into an interface can incur an allocation, which can be detrimental in a tight loop. This pattern isn't terribly common.
package main
import "fmt"
type Result interface {
// a dummy method to limit the possible types that can
// satisfy this interface
IsResult()
}
type Data struct {
ID int
Name string
}
func (d Data) IsResult() {}
type DataError struct {
Message string
ErrorCode string
}
func (err DataError) IsResult() {}
func SomeFunction(isGoodData bool) Result {
if isGoodData {
return Data{ID: 42, Name: "answer"}
}
return DataError{Message: "A thing happened", ErrorCode: "Oops!"}
}
func main() {
fmt.Println(SomeFunction(true))
}
2. Tagged Union (playground)
This case is similar to the previous case, except instead of using an interface, we're using a struct with a tag that tells us which type of data the struct contains (this is similar to a tagged union in C, except the size of the struct is the sum of its potential types instead of the size of its largest potential type). While this takes up more space, it can easily be stack-allocated, thus making it tight-loop friendly (I've used this technique to reduce allocs from O(n) to O(1)). In this case, our tag is a bool because we only have two possible types (Data and DataError), but you could also use a C-like enum.
package main
import (
"fmt"
)
type Data struct {
ID int
Name string
}
type DataError struct {
Message string
ErrorCode string
}
type Result struct {
IsGoodData bool
Data Data
Error DataError
}
// Implements the `fmt.Stringer` interface; this is automatically
// detected and invoked by fmt.Println() and friends
func (r Result) String() string {
if r.IsGoodData {
return fmt.Sprint(r.Data)
}
return fmt.Sprint(r.Error)
}
func SomeFunction(isGoodData bool) Result {
if isGoodData {
return Result{
IsGoodData: true,
Data: Data{ID: 42, Name: "Answer"},
}
}
return Result{
IsGoodData: false,
Error: DataError{
Message: "A thing happened",
ErrorCode: "Oops!",
},
}
}
func main() {
// this bool argument controls whether or not an error is returned
fmt.Println(SomeFunction(true))
}
You can't assign 2 different types that are not "assignable" to the same variable ... unless you use a specific interface signature or empty interface.
https://golang.org/ref/spec#Assignability
that code would compile :
func main() {
var response interface{} // empty interface AKA Object AKA void pointer
response = Data{Id: 100, Name: `Name`}
if true {
response = DataError{Message: `message`, ErrorCode: `code`}
}
log.Println(response)
}
since every type implements empty interface, but you want to do that only if there is no other options.
if 2 types share some methods use a specific interface, for instance (pseudo-code) :
type Responder interface {
Respond() string
}
type Data struct { /* code */
}
func (d Data) Respond() string { return "" }
type DataError struct { /* code */
}
func (d DataError) Respond() string { return "" }
func main() {
var response Responder // declared as interface
response = Data{}
response = DataError{}
fmt.Println(response)
}
Whenever you have doubts a quick scan of the go spec is useful, it is the only authority and pretty well written compared to most specs out there. For the most part the rules are crystal clear, and that's a strength of Go.
Related
I have two different interfaces (from two different packages) that I want to implement. But they conflict, like this:
type InterfaceA interface {
Init()
}
type InterfaceB interface {
Init(name string)
}
type Implementer struct {} // Wants to implement A and B
func (i Implementer) Init() {}
func (i Implementer) Init(name string) {} // Compiler complains
It says "Method redeclared". How can one struct implement both interfaces?
As already answered, this is not possible since Golang does not (and probably will not) support method overloading.
Look at Golang FAQ:
Experience with other languages told us that having a variety of methods with the same name but different signatures was occasionally useful but that it could also be confusing and fragile in practice. Matching only by name and requiring consistency in the types was a major simplifying decision in Go's type system.
It is not possible.
In go you must have a single method signature.
You should rename one method.
The method signatures must match. If you want dependency injection I would recommend the functional option pattern. Functional options are functions that return other functions that are called in a loop in the constructor. Here is an example of how to use functional options and the basics of interfaces in go.
package main
import (
"fmt"
"strconv"
)
type SomeData struct {
data string
}
// SomeData and SomeOtherData both implement SomeInterface and SomeOtherInterface
// SomeInterface and SomeOtherInterface both implement each other.
type SomeInterface interface {
String() string
Set(data string)
}
func (s *SomeData)String() string {
return s.data
}
func (s *SomeData)Set(data string) {
s.data = data
}
// SetDataOption is a functional option that can be used to inject a constructor dep
func SetDataOption(data string) func(*SomeData) {
return func(s *SomeData) {
s.Set(data)
}
}
// NewSomeData is the constructor; it takes in 0 to many functional options and calls each one in a loop.
func NewSomeData(options ...func(s *SomeData)) SomeInterface {
s := new(SomeData)
for _, o := range options {
o(s)
}
return s
}
//********************
type SomeOtherData struct {
data string
i int
}
type SomeOtherInterface interface {
String() string
Set(data string)
}
func (s *SomeOtherData)String() string {
return s.data + " " + strconv.Itoa(s.i)
}
func (s *SomeOtherData)Set(data string) {
s.data = data
}
func SetOtherDataOption(data string) func(*SomeOtherData) {
return func(s *SomeOtherData) {
s.Set(data)
}
}
func SetOtherIntOption(i int) func(*SomeOtherData) {
return func(s *SomeOtherData) {
s.i = i
}
}
// NewSomeOther data works just like NewSomeData only in this case, there are more options to choose from
// you can use none or any of them.
func NewSomeOtherData(options ...func(s *SomeOtherData)) SomeOtherInterface {
s := new(SomeOtherData)
for _, o := range options {
o(s)
}
return s
}
//*********************************
// HandleData accepts an interface
// Regardless of which underlying struct is in the interface, this function will handle
// either by calling the methods on the underlying struct.
func HandleData(si SomeInterface) {
fmt.Println(si) // fmt.Println calls the String() method of your struct if it has one using the Stringer interface
}
func main() {
someData := NewSomeData(SetDataOption("Optional constructor dep"))
someOtherData := NewSomeOtherData(SetOtherDataOption("Other optional constructor dep"), SetOtherIntOption(42))
HandleData(someData) // calls SomeData.String()
HandleData(someOtherData) // calls SomeOtherData.String()
someOtherData = someData // assign the first interface to the second, this works because they both implement each other.
HandleData(someOtherData) // calls SomeData.String() because there is a SomeData in the someOtherData variable.
}
This is a follow up to this question: Interface method with multiple return types
I have two structs which are slightly different. One is about a trade struct, the other about a transfer struct. The goal is to calculate the quantity at the end. Also the trade struct shall implement some specific function not common to the transfer struct and the other way around. At the end they all call a get() function and ultimately return the quantity (type string). I can't come to do something like that qtyGetService(trade{}).calculateA().get() where qtyGetService() and get() can be called from both struct, but calculateA() is a method only for trade struct. Interfaces look at first promising to solve such issues but I'm facing the issue described in that question Interface method with multiple return types that a method in an interface must return a specific type. Returning an interface{} wouldn't be an option either as I would not be able to chain the functions like shown in the example below (not even mentioning the use of reflect).
package main
import (
"fmt"
)
type Trade struct {
q string
// many other attributes
}
type Transfer struct {
q string
// many other attributes
}
type TradeService struct {
q string
// some other attributes
}
type TransferService struct {
q string
// some other attributes
}
type GetQty struct {
q string
// some other attributes
}
func qtyGetTradeService(str *Trade) *TradeService {
// some processing on the initial struct
return &TradeService{
q: str.q + " TradeService ",
}
}
func qtyGetTransferService(str *Transfer) *TransferService {
// some processing on the initial struct
return &TransferService{
q: str.q + " TransferService ",
}
}
func (ts *TradeService) calculateA() *GetQty {
// some processing on ts
return &GetQty{
q: ts.q + " CalculateA ",
}
}
func (ts *TradeService) calculateB() *GetQty {
// some processing on ts
return &GetQty{
q: ts.q + " CalculateB ",
}
}
func (ts *TransferService) calculateC() *GetQty {
// some processing on ts
return &GetQty{
q: ts.q + " CalculateC ",
}
}
func (gq *GetQty) get() string{
// some processing on gq common to both trade and transfer
return gq.q + " CommonGet "
}
func main() {
// this works just fine
fmt.Println(qtyGetTradeService(&Trade{q: "10"}).calculateA().get())
fmt.Println(qtyGetTransferService(&Transfer{q: "10"}).calculateC().get())
// But this would be "better" to do something like this:
fmt.Println(qtyGetService(&Trade{q: "10"}).calculateA().get())
fmt.Println(qtyGetService(&Transfer{q: "10"}).calculateC().get())
}
Link to playground: https://play.golang.org/p/SBCs_O9SL0k
Thx for reposting the question. In the comments of the other question it would have been hard to provide a code example.
I see 2 options you have here:
Option 1:
Create a function calculate on all structs with the same signature. In your example there are no input params, only a return value. If that is not the case, things get a bit more complex and option 2 might be a better fit.
Note: chaining functions makes it harder to use interfaces in Go. You might want to get rid of that.
Example:
type qty interface{
calculate() qty // chaining can be problematic. best no return value here.
get() string // or whatever type get should return
}
func (ts *TradeService) calculate() qty {
ts.calculateA()
return ts
}
func (ts *TransferService) calculate() qty {
ts.calculateC()
return ts
}
func main() {
// Now this should
fmt.Println(qtyGetService(&Trade{q: "10"}).calculate().get())
fmt.Println(qtyGetTransferService(&Transfer{q: "10"}).calculate().get())
// or without chaining (if the return value is removed from `calculate`):
printVal(qtyGetService(&Trade{q: "10"}))
printVal(qtyGetTransferService(&Transfer{q: "10"}))
}
func printVal(service qty) {
service.calculate()
fmt.Println(service.get())
}
Sometimes it makes sense to implement a function on a struct even if it is not needed to satisfy an interface. If there is a service that doesn't need to calculate before calling get just create this function:
func (ts *SomeService) calculate() {}
Now it can be used as qty interface.
Option 2:
It could also be that the cases are not so uniform and harder to bring into a single interface.
Then you could work with multiple interfaces and cast the struct to check if it implements the interface. Only then call the method. This is more or less like a check if the struct has a certain method or not.
type calculatorA interface {
calculateA()
}
type calculatorB interface {
calculateB()
}
type getter interface {
get()
}
func main() {
service := qtyGetService(&Trade{q: "10"})
if ok, s := service.(calculatorA); ok {
s.calculateA()
}
if ok, s := service.(calculatorB); ok {
s.calculateB()
}
var val string
if ok, s := service.(getter); ok {
val = s.get()
}
fmt.Println(val)
}
Hope this is applicable to your case and gives you some ideas.
If you add a GetService() receptor to both Trade and Transfer like this:
func (t Trade) GetService() *TradeService {
return &TradeService{
q: t.q + " TradeService ",
}
}
func (t Transfer) GetService() *TransferService {
return &TransferService{
q: t.q + " TransferService ",
}
}
You will be able to use it like this:
fmt.Println(Trade{q: "10"}.GetService().calculateA().get())
fmt.Println(Transfer{q: "10"}.GetService().calculateC().get())
Seems to be what you are trying to accomplish.
Defining GetService() in a interface would not work because the return type of both implementations is different.
I want to use slacknotificationprovider in the NewNotifier function. How can I do it. Also I want send a string(config.Cfg.SlackWebHookURL) in newNotifier function. What should I do? Also please suggest me some material to get a deeper knowledge of struct and interface in golang.
I also want to know why ProviderType.Slack is not defined as I have mentioned it in ProviderType struct as of SlackNotificationProvider type? Thanks.
type SlackNotificationProvider struct {
SlackWebHookURL string
PostPayload PostPayload
}
type ProviderType struct {
Slack SlackNotificationProvider
Discord DiscordNotificationProvider
}
type Notifier interface {
SendNotification() error
}
func NewNotifier(providerType ProviderType) Notifier {
if providerType == ProviderType.Slack {
return SlackNotificationProvider{
SlackWebHookURL: SlackWebHookURL,
}
} else if providerType == ProviderType.Discord {
return DiscordNotificationProvider{
DiscordWebHookURL: SlackWebHookURL + "/slack",
}
}
return nil
}
slackNotifier := NewNotifier(config.Cfg.SlackWebHookURL)
Errors:
1. cannot use config.Cfg.SlackWebHookURL (type string) as type ProviderType in argument to NewNotifiergo
2. ProviderType.Slack undefined (type ProviderType has no method Slack)go
Golang is a strongly typed language, which means the arguments to your functions are defined and can't be different. Strings are strings and only strings, structs are structs and only structs. Interfaces are golang's way of saying "This can be any struct that has method(s) with the following signatures". So you can't pass a string as a ProviderType and none of your structs actually implement the interface method you've defined, so nothing would work as you've laid it out. To reorganize what you've got into something that might work:
const (
discordType = "discord"
slackType = "slack"
)
// This means this will match any struct that defines a method of
// SendNotification that takes no arguments and returns an error
type Notifier interface {
SendNotification() error
}
type SlackNotificationProvider struct {
WebHookURL string
}
// Adding this method means that it now matches the Notifier interface
func (s *SlackNotificationProvider) SendNotification() error {
// Do the work for slack here
}
type DiscordNotificationProvider struct {
WebHookURL string
}
// Adding this method means that it now matches the Notifier interface
func (s *DiscordNotificationProvider) SendNotification() error {
// Do the work for discord here
}
func NewNotifier(uri, typ string) Notifier {
switch typ {
case slackType:
return SlackNotificationProvider{
WebHookURL: uri,
}
case discordType:
return DiscordNotificationProvider{
WebHookURL: uri + "/slack",
}
}
return nil
}
// you'll need some way to figure out what type this is
// could be a parser or something, or you could just pass it
uri := config.Cfg.SlackWebHookURL
typ := getTypeOfWebhook(uri)
slackNotifier := NewNotifier(uri, typ)
As far as documentation to help with this, the "Go By Example" stuff is good, and I see other people have already linked that. That said, a struct with one method feels like it should be a function, which you can also define as a type to allow you to pass back a few things. Example:
type Foo func(string) string
func printer(f Foo, s string) {
fmt.Println(f(s))
}
func fnUpper(s string) string {
return strings.ToUpper(s)
}
func fnLower(s string) string {
return strings.ToLower(s)
}
func main() {
printer(fnUpper, "foo")
printer(fnLower, "BAR")
}
I have the following code:
package vault
type Client interface {
GetHealth() error
}
func (c DefaultClient) GetHealth () error {
resp := &VaultHealthResponse{}
err := c.get(resp, "/v1/sys/health")
if err != nil {
return err
}
return nil;
}
Now, I want to use this function as part of this struct:
type DependencyHealthFunction func() error
type Dependency struct {
Name string `json:"name"`
Required bool `json:"required"`
Healthy bool `json:"healthy"`
Error error `json:"error,omitempty"`
HealthFunction DependencyHealthFunction
}
Basically, set the value of HealthFunction to GetHealth. Now, when I do the following:
func (config *Config) GetDependencies() *health.Dependency {
vaultDependency := health.Dependency{
Name: "Vault",
Required: true,
Healthy: true,
HealthFunction: vault.Client.GetHealth,
}
temp1 := &vaultDependency
return temp1;
}
This gives me an error and it says cannot use vault.Client.GetHealth (type func(vault.Client) error) as type health.DependencyHealthFunction in field value. How can I do this?
Edit: How DependencyHealthFunction is used?
As its part of Dependency struct, it's simply used as following: d.HealthFunction() where d is a variable of type *Dependency.
This is abstract:
HealthFunction: vault.Client.GetHealth,
If we were to call HealthFunction(), what code do you expect to run? vault.Client.GetHealth is just a promise that such a function exists; it isn't a function itself. Client is just an interface.
You need to create something that conforms to Client and pass its GetHealth. For example, if you had a existing DefaultClient such as:
defaultClient := DefaultClient{}
Then you could pass its function:
HealthFunction: defaultClient.GetHealth,
Now when you later call HealthFunction() it will be the same as calling defaultClient.GetHealth().
https://play.golang.org/p/9Lw7uc0GaE
I believe the issue is related to understanding how interfaces are treated in Go.
An interface simply defines a method or set of methods that a particular type must satisfy to be considered as "implementing" the interface.
For example:
import "fmt"
type Greeter interface {
SayHello() string
}
type EnglishGreeter struct{}
// Satisfaction of SayHello method
func (eg *EnglishGreeter) SayHello() string {
return "Hello"
}
type SpanishGreeter struct{}
func (sg *SpanishGreeter) SayHello() string {
return "Ola"
}
func GreetPerson(g Greeter) {
fmt.Println(g.SayHello())
}
func main() {
eg := &EnglishGreeter{}
sg := &SpanishGreeter{}
// greet person in english
GreetPerson(eg)
// greet person in spanish
GreetPerson(sg)
}
You can add this behavior into a custom struct by simply having a Greeter field inside the struct. ie
type FrontEntrance struct {
EntranceGreeter Greeter
}
fe := &FrontEntrance { EntranceGreeter: &EnglishGreeter{} }
// then call the SayHello() method like this
fe.EntranceGreeter.SayHello()
Interfaces in golang are useful for composing common expected behavior for types based on the methods that they satisfy.
Hope this helps.
Below I have an example of one structure which embeds another. I'm trying to figure out how to pass the more specific structure pointer to be stored in a less specific one. You can think of it as a collection. Wrapping in an interface doesn't seem to work, as doing so would make a copy, which isn't valid for structs with locks. Ideas?
package stackoverflow
import "sync"
type CoolerThingWithLock struct {
fancyStuff string
ThingWithLock
}
func NewCoolerThingWithLock() *CoolerThingWithLock {
coolerThingWithLock := &CoolerThingWithLock{}
coolerThingWithLock.InitThingWithLock()
return coolerThingWithLock
}
type ThingWithLock struct {
value int
lock sync.Mutex
children []*ThingWithLock
}
func (thingWithLock *ThingWithLock) InitThingWithLock() {
thingWithLock.children = make([]*ThingWithLock, 0)
}
func NewThingWithLock() *ThingWithLock {
newThingWithLock := &ThingWithLock{}
newThingWithLock.InitThingWithLock()
return newThingWithLock
}
func (thingWithLock *ThingWithLock) AddChild(newChild *ThingWithLock) {
thingWithLock.children = append(thingWithLock.children, newChild)
}
func (thingWithLock *ThingWithLock) SetValue(newValue int) {
thingWithLock.lock.Lock()
defer thingWithLock.lock.Unlock()
thingWithLock.value = newValue
for _, child := range thingWithLock.children {
child.SetValue(newValue)
}
}
func main() {
thingOne := NewThingWithLock()
thingTwo := NewCoolerThingWithLock()
thingOne.AddChild(thingTwo)
thingOne.SetValue(42)
}
Error: cannot use thingTwo (type *CoolerThingWithLock) as type
*ThingWithLock in argument to thingOne.AddChild
It's impossible to store the wrapping type in []*ThignWithLock since go has no notion of structural subtyping.
Your assertion that an interface will result in copying is incorrect, and you can get the desired effect by doing:
type InterfaceOfThingThatParticipatesInAHierarchy interface {
AddChild(InterfaceOfThingThatParticipatesInAHierarchy)
SetValue(int)
}
type ThingWithLock struct {
...
children []InterfaceOfThingThatParticipatesInAHierarchy
}
func (thingWithLock *ThingWithLock) AddChild(newChild InterfaceOfThingThatParticipatesInAHierarchy) { ... }
As long as the interface is implemented on a *ThingWithLock and not ThingWithLock, there will be no copying of the receiver struct itself, only the pointer to the struct will be copied on the stack.