0
0

More than 1 year has passed since last update.

Go : 名前付き返り値がある状態で、returnのみ記述したときの挙動

Posted at
  • 名前付き返り値が設定されている状態だと、returnだけ記載することができ、その場合は名前付き返り値が暗黙的に返却される。
func example()(ret string){
    ret = "hello world"
    return
}

func main(){
    fmt.Println(example()) // hello world
}

  • 一方で、名前付き返り値を設定しておきながら、別の変数を返却することも可能
func example() (ret string) {
    ret = "hello world"
    ret2 := "goodbye world"
    return ret2 //新たに定義した変数を返す
}

func main() {
    fmt.Println(example()) // goodbye world
}
  • コンパイルエラーにならない。名前付き返り値を設定している意味がないし、予期せぬ挙動を招いてしまう可能性があるので、名前付きの方を返却するように修正するか、あるいは元から名前付きにしないようにする。
0
0
0

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
0
0