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

go修行2日目 変数定数

Posted at

変数

  • varを使った変数宣言は関数の外でも使える
  • xiなどの短縮版の変数宣言は関数の中でしか使えない
package main

import "fmt"

var (
	i    int     = 1
	f64  float64 = 1.2
	s    string  = "test"
	t, f bool    = true, false
)

func main() {
	fmt.Println(i, f64, s, t, f)

	xi := 666
	xf64 := 66.6
	xs := "aaa"
	xt, xf := false, true
	fmt.Println(xi, xf64, xs, xt, xf)
	fmt.Printf("")
}

出力

yuta@DESKTOP-V36210S:/mnt/c/gostudy$ ./test
1 1.2 test true false
666 66.6 aaa false true
yuta@DESKTOP-V36210S:/mnt/c/gostudy$ 

定数

  • constで定数を指定する
  • ユーザー、パスワードなどは定数がいいのだと思yyk

package main

import "fmt"

const Pi = 3.14

const (
	username = "user"
	password = "pass"
)

func main() {
	fmt.Println(Pi, username, password)
}

出力

yuta@DESKTOP-V36210S:/mnt/c/gostudy$ ./test
3.14 user pass

数値型の演算


package main

import "fmt"

func main() {
	fmt.Println("---数値型---")
	var (
		u8  uint8     = 255 //32bitか64bit環境かでの環境依存
		i8  int8      = 127 //
		f32 float64   = 0.2
		c64 complex64 = -5 + 12i
	)
	fmt.Println(u8, i8, f32, c64)
	fmt.Printf("type=%T value=%v", u8, u8)
	fmt.Println()

	fmt.Println("---演算---")
	fmt.Println("1 + 1 =", 1+1)
	fmt.Println("10.0 / 3 =", 10.0/3)
	fmt.Println("10 % 3 =", 10%3)
	fmt.Println()

	fmt.Println("---シフト演算---")
	fmt.Println(1 << 0) //0001 → 0001
	fmt.Println(1 << 1) //0001 → 0010
	fmt.Println(1 << 2) //0001 → 0100
	fmt.Println(1 << 3) //0001 → 1000
	fmt.Println()
}

出力

---数値型---
255 127 0.2 (-5+12i)
type=uint8 value=255
---演算---
1 + 1 = 2
10.0 / 3 = 3.3333333333333335
10 % 3 = 1

---シフト演算---
1
2
4
8

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?