-1

Let say that I have

connection := pool.GetConnection().(*DummyConnection)

where pool.GetConnection returns interface{} and I would like to cast it to DummyConnection.

I would like to change the GetConnection interface to return error. The code starts looking like this:

connectionInterface, err := pool.GetConnection()
connection := connectionInterface.(*DummyConnection)

I am wondering, can I avoid the need of helper variable and have these on a single line?

gsf
  • 6,612
  • 7
  • 35
  • 64
  • 1
    Possible duplicate of [Go: multiple value in single-value context](http://stackoverflow.com/questions/28227095/go-multiple-value-in-single-value-context) – icza May 18 '16 at 22:21
  • Nope, in my question I do not want to ignore the err or predefine behavior - I want to apply a modification over one of the returned values ... but the solution is similar, I just need to create helper function. I am sorry - I am new to golang. – gsf May 18 '16 at 22:25

2 Answers2

3

You cannot combine those two statements because the function returns a pair of values and there is no way to state which of them you would like to do the type assertion on. With the assignment it works because the identifiers are ordered as are the the return values, but how do you expect the compiler to infer which value you'd like to execute the type assertion on?

I wouldn't recommend trying to reduce your code too much in Go. It's not really consistent with how the language is designed and I believe that is deliberate. The philosophy is that this is easier to read because there isn't much abstraction and also because you're not given so many options to achieve the same result. Anyway, you wouldn't really be saving much with that type assertion and any function call like this requires a few additional lines of code for error handling. It's pretty much the norm in Go.

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
-1

a solution in some kind. not reduce the code, but reduce variables in out function scope, by moving it to a anonymous inner function.

package main

import "fmt"

type t struct{}

func foo()(interface{},error){
    return &t{},nil
}

func main() {
    var myT *t
    myT, err := func() (*t,error){
        i,e:=foo()
        return i.(*t),e
    }()
    fmt.Println(myT,err)
}
Jiang YD
  • 3,205
  • 1
  • 14
  • 20