LoginSignup
0
0

More than 1 year has passed since last update.

【自己学習】Go言語を学ぶ(2)

Last updated at Posted at 2022-06-19

公式チュートリアルから基本を学ぶ
https://go-tour-jp.appspot.com/list

Functions

関数は、0個以上の引数を取ることができます。
この例では、 add 関数は、 int 型の2つのパラメータを取ります。
変数名の 後ろ に型名を書くことに注意してください。

概要

  • 型指定が必要

  • mainの引数から別のFunctionsを読み込んで返せる

  • 必ずfunction内でreturnを忘れないこと

  • サンプルコード

package main

import "fmt"

func add(x int, y int) int {
  return x + y
}

func main() {
  fmt.Println(add(42, 13))
}
  • 結果:55

x int, y intは x, y intに省略できる

  • サンプルコード
package main

import "fmt"

func add(x, y int) int {
  return x + y
}

func main() {
  fmt.Println(add(42, 13))
}

複数の戻り値を返す

以下のswap 関数は2つの string を返します。

  • サンプルコード
package main

import "fmt"

func swap(x, y string) (string, string) {
  return y, x
}

func main() {
  a, b := swap("hello", "world")
  fmt.Println(a, b)
}

  • 結果: world hello

Goでの戻り値となる変数に名前をつける

  • サンプルコード
package main

import "fmt"

func split(sum int) (x, y int) {
  x = sum * 4 / 9
  y = sum - x
  return
}

func main() {
  fmt.Println(split(17))
}

※ xの計算: 17 * 4 /9 = 7.555
※ yの計算: 17 - 7 = 10

  • 結果: 7 10
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