3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

golangの名前付き戻り値に関して

Last updated at Posted at 2020-01-22

名前付き変数はtour of goで紹介されているように、関数の最初で変数宣言したのと同様になる。

この時、nameの変数のスコープはfugafuga()に対して関数渡しで渡した関数から参照できるため、下記コードは問題なく動く。

package main

import "fmt"

func fugafuga(f func() error, logger func(err error)) error {
	f()
	return nil
}

func hogehoge() (name string, err error) {
	fugafuga(func() error {
		name = "test"
		return nil
	},
		func(err error) {
		})
	return
}

func main() {
	n, _ := hogehoge()
	fmt.Println(n)
}

出力結果

$ go run main.go
test
3
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?