LoginSignup
0
0

More than 3 years have passed since last update.

go修行11日目 タイプアサーションとか

Posted at

タイプアサーション

  • 型変換をすること
  • interface型で受け取ると型の判断ができないため

intger型

package main

import "fmt"

func do(i interface{}){
    // タイプアサーション interface型だとそのまま利用できないのでintergerへ変換する必要がある
    ii := i.(int)
    ii *= 2
    fmt.Println(ii)
}

func main(){
    var i interface{} = 10
    do(i)
}

出力

20

string型

package main

import "fmt"

func do(s interface{}){
    ss := s.(string)
    fmt.Println(ss + "!")
}

func main(){
    do("Mike")
}
Mike!

Switch type


package main

import "fmt"

func do(i interface{}){
    // いろいろな型に対応できるようにできるswitch type
    switch v := i.(type){
    // intgerの場合
    case int:
        fmt.Println(v * 2)
    // stringの場合
    case string:
        fmt.Println(v + "!")
  // それ以外
    default:
        fmt.Println("I don't know %T%n", v)
    }
}

func main(){
    // string
    do("Mike")
    // integer
    do(10)
    // boolean
    do(true)
}
Mike!
20
I don't know %T%n true

Stringer


package main

import "fmt"

type Person struct{
    Name string
    Age int
}

// String()で出力方法を変えられる
func (p Person) String() string{
    // 名前だけ返す(年齢は返さない)
    return fmt.Sprintf("My name is %v", p.Name)
}

func main() {
    mike := Person{"Mike", 22}
    fmt.Println(mike)
}
My name is Mike

カスタムエラー


package main

import (
    "fmt"
)

type UserNotFound struct{
    Username string
}

func (e *UserNotFound) Error() string{
    return fmt.Sprintf("User not found: %v", e.Username)
}

func myFunc() error{
    // 何かエラーが出たら
    ok := false
    // okならnil
    if ok {
        return nil
    }
    // ユーザーが見つからなかったら
    return &UserNotFound{Username: "Mike"}
}

func main() {
    if err := myFunc(); err != nil {
        fmt.Println(err)
    }
}
User not found: Mike

goroutine

  • 並列処理

package main

import (
    "fmt"
    "sync"
)

func goroutine(s string, wg *sync.WaitGroup){
    for i := 0; i < 5; i++{
        // time.Sleep(100 * time.Millisecond)
        fmt.Println(s)
    }
    wg.Done()
}

func normal(s string){
    for i := 0; i < 5; i++{
        // time.Sleep(100 * time.Millisecond)
        fmt.Println(s)
    }
}

func main(){
    var wg sync.WaitGroup
    wg.Add(1)
    // 並列処理
    go goroutine("world", &wg)
    normal("hello")
    // time.Sleep(2000 * time.Millisecond)
    wg.Wait()
}
hello
hello
hello
hello
hello
world
world
world
world
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