Go言語 インターフェース

package main

import "fmt"

type englishScoreType int
type mathScoreType int

func (e englishScoreType) isPassed() bool {
    return e >= 80
}

func (m mathScoreType) isPassed() bool {
    return m >= 70
}

type passChecker interface {
    isPassed() bool
}

func showResult(score passChecker) {
    if score.isPassed() {
        fmt.Println("Pass!")
    } else {
        fmt.Println("Fail...")
    }
}

func main() {
    englishScore := englishScoreType(90)
    mathScore := mathScoreType(50)

    showResult(englishScore)
    showResult(mathScore)
}

Go言語 構造体

package main

import "fmt"

type studentType struct {
    name string
    score scoreType
}

type scoreType struct {
    subject string
    points int
}

func (s scoreType) isPassed() bool {
    if s.points >= 70 {
        return true
    } else {
        return false
    }
}

func main() {
    taro := studentType{
        name:  "Taro",
        score: scoreType{
            subject: "Math",
            points:  85,
        },
    }

    fmt.Println(taro.name)
    fmt.Println(taro.score.subject)
    fmt.Println(taro.score.points)
    fmt.Println(taro.score.isPassed())
}

Go言語 ジェネリクス

package main

import "fmt"

// func showIntThreeTimes(num int) {
//     fmt.Println(num)
//     fmt.Println(num)
//     fmt.Println(num)
// }

// func showFloat64ThreeTimes(num float64) {
//     fmt.Println(num)
//     fmt.Println(num)
//     fmt.Println(num)
// }

func showThreeTimes[T any](num T) {
    fmt.Println(num)
    fmt.Println(num)
    fmt.Println(num)
}

func main() {
    // showIntThreeTimes(3)
    // showFloat64ThreeTimes(5.2)
    showThreeTimes(3)
    showThreeTimes(5.2)
}