1
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?

golangでスマートにswapする方法

Posted at

結論

以下のように変数aとbをswapできます。a, bは同じ型の前提。

swap_example.go
a, b = b, a

解説

golangの関数は複数の値を返せます[1]が、それを活用してこのような記載もできます。golangにはswap関数が用意されていませんが、このように簡単にswapできるからだと思われます。Google検索しても日本語の記事が出てこなかったため本記事を作成しました。

参考

[1] https://go.dev/doc/effective_go#multiple-returns

1
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
1
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?