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 1 year has passed since last update.

入門GOプログラミング Lesson4~10

Last updated at Posted at 2023-03-04

省略形式の変数定義

var count = 10
conut := 10

for文の省略形式(C, Java, Javascriptと同じ構文)


for count := 10; count > 0; count-- {
    fmt.Println(count)
}

グローバル変数

var era = AD;// グローバル変数
func main() {
	count := 10
	for count = 10; count > 0; count-- {
		fmt.Println(count)
	}
}

省略形式による変数定義は使用不可

Lesson5

練習問題 解答例

package main
import (
	"fmt"
	"math/rand"
)
func main() {
    // 各チケットの要素の配列を定義する
	spaceLineArr := [...]string{"Virgin Galactic", "SpaceX", "Space Adventures"}
	tripTypeArr := [...]string{"Round-trip", "One-way"}
    // フォーマットを定義する
	fmt.Printf("%-18v %-6v %-13v %v\n", "spaceline", "Days", "Trip type", "Price")
	fmt.Println("==============================================")
	for i := 0; i < 10; i++ {
        // 各配列からチケットの要素をランダム選択する
		spaceLineSelectNum := rand.Intn(3)
		tripTypeNum := rand.Intn(2)
		days := rand.Intn(100) + 1
		price := rand.Intn(100) + 1
		fmt.Printf("%-18v %-6v %-13v %v\n", spaceLineArr[spaceLineSelectNum],
			days, tripTypeArr[tripTypeNum], price)
	}
}

Lesson6 型

ゼロ値

値無しで変数が宣言されたとき、自動的に0が代入される

var price float64
price := 0.0 // 同上

桁数を指定した表示方法

var third float64 = 1.0 / 3
fmt.Println(third)
fmt.Printf("%v\n", third)// 0.33333....
fmt.Printf("%f\n", third)// 0.33333....
fmt.Printf("%.3f\n", third)// 0.333
fmt.Printf("%4.2f\n", third)// 0.33

%n.Nf
n=幅
----
0.33
 --
 N=精度

0でパディング

fmt.Printf("%05.2f\n", third)

■練習問題 解答例


Lesson7 整数

整数型の種類

int8
uint8
int16
uint16
int32
uint32
int64
uint64

例えばRGBを表したいとき

	var red, green, blue uint8 = 0x00, 0x80, 0xd5
	fmt.Printf("color : 0x%02x%02x%02x", red, green, blue)
// color : 0x0080d5

■練習問題

Lesson8

Lesson9

文字列リテラル

peace := "peace"
var peace = "peace"// 同上
var peace = "peace"// 同上
var peace // ""と同じ
  • 別文字への代入は可能(書き換えはPython, Java, Javascript同様で不可能(イミュータブル))
message[5] := "shalom"
message[5] = d // error : cannot assign to message[5]

rune型

あいうえおにstring型でアクセス

	s := "あいうえお"

	for i := 0; i < len(s); i++ {
		b := s[i] // byte
		fmt.Printf("0x%02x\n", b)
結果
0xe3
0x81
0x82
0xe3
0x81
0x84
0xe3
0x81
0x86
0xe3
0x81
0x88
0xe3
0x81
0x8a
	}

rune型でデコード

s := "あいうえお"
for _, c := range s {
    fmt.Printf("%v\n", string(c))
}

■練習問題

Lesson10 型変換

int -> float64

age := 41
marsAge := float64(age)
fmt.Println(marsAge)

Interger -> ASCII

countDown := 10
fmt.Println("発射まであと" + strconv.Itoa(countDown) + "秒")
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?