简体   繁体   中英

Go. Multiple-value in single-value context in Interface

I read below topic

Go: multiple value in single-value context

But I don't understand this explain in my case. May be that's way because I want to use interface

I get error multiple-value NewObject() in single-value context in below case

type Facade interface {
    GetOne() int
}

type ObjectOne struct{
    one int
}

func NewObject()(Facade, error){
    o := &ObjectOne{}
    return o , errors.New("Some funny error")
}

func(o * ObjectOne)GetOne()int{
    return 1
}

func SomeWhereInCode(){
    newFacade , err := Facade(NewObject())
// And here. I get error probbably because Facade constructor return one arguments (interface) and NewObject() return two. How should be ? 
}

I also tryed pass error as pointer to ObjectOne but still get error compiler

type Facade interface {
    GetOne() int
}

type ObjectOne struct{
    one int
}

func NewObject(facadeError* error)(Facade, error){
    o := &ObjectOne{}
    *facadeError = errors.New("Some funny error")
    return o , *facadeError
}

func(o * ObjectOne)GetOne()int{
    return 1
}

func SomeWhereInCode(){
    var facadeError = error()
    newFacade , err := Facade(NewObject(&facadeError))
}

In the expression:

newFacade , err := Facade(NewObject())

Facade(NewObject()) is not a constructor but an explicit type conversion. You do not need it at all because NewObject() , being a constructor already, returns a Facade type and an error. So just:

newFacade , err := NewObject()

should work seems to me.

The problem is that NewObject has multiple return values and you can't chain or next functions that return multiple values (in the same line).

It's unclear why you are trying to call Facade(...) on a return value that you think should be a Facade, are you doing a type conversion?

Try getting out the value and dealing with the error and then calling the outside function.

type Facade interface {
    GetOne() int
}

type ObjectOne struct{
    one int
}

func NewObject()(Facade, error){
    o := &ObjectOne{}
    return o , errors.New("Some funny error")
}

func(o * ObjectOne)GetOne()int{
    return 1
}

func SomeWhereInCode(){
    newFacade , err := NewObject())
    if err != nil {
        // handle err or panic
    }
    Facade(newFacade)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM