Golang调用方法的最高效方式

huangapple go评论70阅读模式
英文:

Golang most efficient way to invoke method`s together

问题

我正在寻找一种最有效的方法来同时调用几个方法。

基本上,我想要的是同时调用这些方法,如果出现错误则返回错误,否则返回结构体类型。

这段代码是可以工作的,但是我无法获取结构体类型或错误,并且我不确定这是否是正确的方式。

go func() (structType, error) {
    structType, err = sm.MethodA() // 返回结构体类型或错误
    err = sm.MethodB() // 返回错误或nil
    return structType, err
}()
英文:

im looking for the most efficient way to invoke couple of method
together.

Basically what im trying to to is invoke those method together and if something went wrong return error else return the struct Type.

This code is working but i can't get the struct type or error and im not sure if its the correct way.

go func()(struct,err) {
		struct,err= sm.MethodA()//return struct type or error
		 err = sm.MethodB()//return error or nill
return struct,err
	}()

答案1

得分: 0

在Go语言中,惯用的做法是返回两个值,并针对错误值进行nil检查。

例如:

func myFunc(sm SomeStruct) (MyStruct, error) {
  s, err := sm.MethodA()
  if err != nil {
    return nil, err
  }
  if err := sm.MethodB(); err != nil {
    return nil, err
  }

  return s, nil 
}

需要注意的一点是,你正在一个goroutine中运行函数。在该goroutine中的任何返回值都不会返回到主goroutine。

为了获取该goroutine的返回值,你必须使用通道来等待这些值。

在你的情况下:

errChan := make(chan error)
retChan := make(chan SomeStructType)

go func() {
    myVal, err := sm.MethodA()
    if err != nil {
        errChan <- err
        return
    }
    
    if err := sm.MethodB(); err != nil {
        errChan <- err
        return
    }

    retChan <- myVal
}()

select {
case err := <-errChan:
    fmt.Println(err)
case val := <-retChan:
    fmt.Printf("My value: %v\n", val)
}

你可以在这里进行调试以更好地理解它:

http://play.golang.org/p/TtfFIZerhk

英文:

In Go, it's idiomatic to return the two values and check for nil against the error

For example:

func myFunc(sm SomeStruct) (MyStruct, error) {
  s, err := sm.MethodA()
  if err != nil {
    return nil, err
  }
  if err := sm.MethodB(); err != nil {
    return nil, err
  }

  return s, nil 
}

One thing to note, is that you're running your function in a goroutine. Any return value inside that goroutine won't be returned to your main goroutine.

In order to get the return values for that go routine you must use channels that will wait for the values.

In your case

errChan := make(chan error)
retChan := make(chan SomeStructType)

go func() {
	myVal, err := sm.MethodA()
	if err != nil {
		errChan &lt;- err
		return
	}
	
	if err := sm.MethodB(); err != nil {
		errChan &lt;- err
		return
	}

	retChan &lt;- myVal
}()

select {
case err := &lt;-errChan:
	fmt.Println(err)
case val := &lt;-retChan:
	fmt.Printf(&quot;My value: %v\n&quot;, val)
}

You can mess around with it here to make more sense out of it:

http://play.golang.org/p/TtfFIZerhk

huangapple
  • 本文由 发表于 2015年3月29日 22:21:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/29330263.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定