コンテンツにスキップ

Go/true

出典: フリー教科書『ウィキブックス(Wikibooks)』
< Go


Goのtrueについて

[編集]

Goにおけるtrueは、bool型の真値を表す事前宣言された識別子(プリミティブ定数)です。falseと対になる基本的な真偽値の一つとして、条件式や論理演算で広く使用されます。

基本情報

[編集]
  • truebool型のリテラル値
  • 変更不可能な組み込み定数
  • if文などの条件式で真を表現する
  • 論理演算の結果として得られる値の一つ
  • 定義済みの識別子(キーワードではない)

他のキーワードとの組み合わせ

[編集]

変数宣言との組み合わせ

[編集]
var isActive bool = true
enabled := true  // 型推論で bool 型になる

定数定義との組み合わせ

[編集]
const DEBUG bool = true
const (
    FEATURE_ENABLED bool = true
    STRICT_MODE     bool = true
)

関数パラメータと戻り値

[編集]
func isEvenNumber(n int) bool {
    if n%2 == 0 {
        return true
    }
    return false
}

func processWithLogging(data []byte, enableLogging bool) []byte {
    if enableLogging == true { // 通常は単に if enableLogging と書く
        log.Println("処理開始")
    }
    // 処理ロジック
    return data
}

条件式(if文)

[編集]
if someCondition == true {
    // 条件が真の場合の処理
}

// より一般的にはこのように書く
if someCondition {
    // 条件が真の場合の処理
}

if !false {
    // これもtrue
}

論理演算子

[編集]
a, b := true, false

and := a && b  // false
or := a || b   // true
not := !a      // false

// 複合条件
result := (a || b) && true  // true

switch文

[編集]
isValid := true

switch isValid {
case true:
    fmt.Println("有効です")
case false:
    fmt.Println("無効です")
}

// 式を使用したswitch
switch {
case x > 0 && true:
    fmt.Println("xは正の数です")
case x < 0 && true:
    fmt.Println("xは負の数です")
default:
    fmt.Println("xはゼロです")
}

for文のループ制御

[編集]
isRunning := true
count := 0

// trueを使った無限ループ
for true {
    count++
    if count >= 10 {
        break
    }
}

// より一般的にはこのように書く
for {  // 条件を省略すると true と見なされる
    count++
    if count >= 20 {
        break
    }
}

// 条件付きループ
running := true
for running == true {
    // 処理
    running = checkShouldContinue()
}

マップとスライス

[編集]
// キーの存在確認
userRoles := map[string]string{
    "alice": "admin",
    "bob":   "user",
}

if role, exists := userRoles["alice"]; exists == true {
    fmt.Println("Alice's role:", role)
}

// スライスの要素をbool値にする
permissions := []bool{true, false, true, true}

構造体のフィールド

[編集]
type User struct {
    Name     string
    IsActive bool
    IsAdmin  bool
}

alice := User{
    Name:     "Alice",
    IsActive: true,
    IsAdmin:  true,
}

if alice.IsAdmin == true && alice.IsActive == true {
    fmt.Println(alice.Name, "は管理者でアクティブです")
}

一般的なユースケース

[編集]
  1. 条件分岐の制御
       func processRequest(req Request) Response {
           if req.IsValid() {
               // 有効なリクエストの処理
               return successResponse()
           }
           return errorResponse("無効なリクエスト")
       }
    
  2. フラグとオプション設定
       type Config struct {
           Debug      bool
           EnableLogs bool
           StrictMode bool
       }
       
       config := Config{
           Debug:      true,
           EnableLogs: true,
           StrictMode: false,
       }
       
       if config.Debug == true {
           fmt.Println("デバッグモードが有効です")
       }
    
  3. バリデーション
       func validateEmail(email string) bool {
           // 電子メールの形式をチェック
           match := regexp.MustCompile(`.+@.+\..+`).MatchString(email)
           return match // true または false を返す
       }
       
       if validateEmail(userEmail) == true {
           sendConfirmation(userEmail)
       } else {
           showError("無効なメールアドレスです")
       }
    
  4. 論理フラグとビットマスク
       const (
           CanRead  = 1 << iota // 1
           CanWrite             // 2
           CanExec              // 4
       )
       
       func hasPermission(permissions int, permission int) bool {
           return permissions&permission != 0
       }
       
       userPerms := CanRead | CanWrite
       
       if hasPermission(userPerms, CanWrite) == true {
           fmt.Println("書き込み権限があります")
       }
    
  5. 関数の結果に基づく処理
       func divide(a, b float64) (float64, bool) {
           if b == 0 {
               return 0, false
           }
           return a / b, true
       }
       
       result, success := divide(10, 2)
       if success == true {
           fmt.Println("計算結果:", result)
       } else {
           fmt.Println("ゼロ除算エラー")
       }
    
  6. 開始/停止処理
       type Service struct {
           IsRunning bool
       }
       
       func (s *Service) Start() bool {
           if s.IsRunning == true {
               return false // すでに実行中
           }
           
           // サービス開始処理
           s.IsRunning = true
           return true
       }
       
       func (s *Service) Stop() {
           s.IsRunning = false
       }
    
  7. 条件付きテキスト表示
       type Person struct {
           Name    string
           IsAdmin bool
       }
       
       func getGreeting(p Person) string {
           greeting := "こんにちは、" + p.Name
           
           if p.IsAdmin == true {
               greeting += "さん(管理者)"
           } else {
               greeting += "さん"
           }
           
           return greeting
       }
    
  8. セットの実装
       type StringSet map[string]bool
       
       func NewStringSet() StringSet {
           return make(StringSet)
       }
       
       func (s StringSet) Add(item string) {
           s[item] = true
       }
       
       func (s StringSet) Contains(item string) bool {
           _, exists := s[item]
           return exists
       }
       
       func main() {
           set := NewStringSet()
           set.Add("apple")
           set.Add("banana")
           
           if set.Contains("apple") == true {
               fmt.Println("セットにappleが含まれています")
           }
       }
    
  9. テスト関数
       import "testing"
       
       func TestAddition(t *testing.T) {
           result := Add(2, 3)
           expected := 5
           
           if result == expected {
               // テスト成功
           } else {
               t.Errorf("Add(2, 3)の結果が%dになるはずが、%dになりました", expected, result)
           }
           
           // または
           if result != expected {
               t.Errorf("Add(2, 3)の結果が%dになるはずが、%dになりました", expected, result)
           }
       }
    
  10. チャネルの閉鎖状態確認
        ch := make(chan int)
        
        // 別のゴルーチンでチャネルを閉じる
        go func() {
            // 何か処理
            close(ch)
        }()
        
        // チャネルが閉じられているか確認
        val, ok := <-ch
        if ok == true {
            fmt.Println("受信した値:", val)
        } else {
            fmt.Println("チャネルが閉じられています")
        }
    
  11. JSONのブール値フィールド
        type Settings struct {
            EnableNotifications bool `json:"enable_notifications"`
            DarkMode           bool `json:"dark_mode"`
        }
        
        settings := Settings{
            EnableNotifications: true,
            DarkMode:           false,
        }
        
        jsonData, _ := json.Marshal(settings)
        fmt.Println(string(jsonData))
        // 出力: {"enable_notifications":true,"dark_mode":false}
    
  12. フラグパッケージを使用したコマンドライン引数
        import "flag"
        
        func main() {
            verbose := flag.Bool("verbose", false, "詳細出力を有効にする")
            flag.Parse()
            
            if *verbose == true {
                fmt.Println("詳細モードが有効です")
            }
        }
        // 実行: ./program -verbose
    
  13. 条件付きコンパイル
        // +build debug
    
        package main
        
        const DEBUG bool = true
        
        // +build !debug
        
        package main
        
        const DEBUG bool = false
    
  14. 並行処理での同期
        done := make(chan bool)
        
        go func() {
            // バックグラウンド処理
            time.Sleep(2 * time.Second)
            done <- true // 処理完了を通知
        }()
        
        // 処理の完了を待つ
        <-done
        fmt.Println("処理が完了しました")
    
  15. 条件付きHTML生成
        type TemplateData struct {
            Username string
            IsAdmin  bool
        }
        
        // テンプレート内で
        /*
        {{if .IsAdmin}}
            <div class="admin-panel">
                <h2>管理者パネル</h2>
                <!-- 管理者用コンテンツ -->
            </div>
        {{end}}
        */
    

特殊なユースケースと注意点

[編集]
  1. trueの評価
    Goでは、条件式で== trueは冗長であり、通常は省略されます。
       // 推奨
       if someCondition {
           // 処理
       }
       
       // 冗長(あまり推奨されない)
       if someCondition == true {
           // 処理
       }
    
  2. bool値と他の型の変換
    Goでは、C言語などと異なり、bool値と数値型の間の自動変換はありません。
       // エラー - コンパイルされない
       // i := 1
       // var b bool = i
       
       // 正しい方法
       i := 1
       var b bool = i != 0
    
  3. trueのストリング表現
       s1 := fmt.Sprintf("%t", true)      // "true"
       s2 := strconv.FormatBool(true)     // "true"
       
       b1, _ := strconv.ParseBool("true") // true
       b2, _ := strconv.ParseBool("TRUE") // true
       b3, _ := strconv.ParseBool("True") // true
       b4, _ := strconv.ParseBool("t")    // true
       b5, _ := strconv.ParseBool("1")    // true
    
  4. インターフェース型からのbool取得
       func checkValue(v interface{}) {
           if b, ok := v.(bool); ok && b == true {
               fmt.Println("値はtrueです")
           } else if ok {
               fmt.Println("値はfalseです")
           } else {
               fmt.Println("値はbool型ではありません")
           }
       }
    
  5. カスタムbool型の定義
       type OnOff bool
       
       const (
           On  OnOff = true
           Off OnOff = false
       )
       
       func (o OnOff) String() string {
           if o == true {
               return "ON"
           }
           return "OFF"
       }
       
       status := On
       if status == true {
           fmt.Println("ステータスはONです")
       }
    
  6. ポインタ型のbool
       type Feature struct {
           Name   string
           Active *bool // nilになる可能性がある
       }
       
       func NewFeature(name string) Feature {
           return Feature{
               Name: name,
               // Active: nilのまま(未設定)
           }
       }
       
       func EnableFeature(f *Feature) {
           active := true
           f.Active = &active
       }
       
       func IsFeatureEnabled(f Feature) bool {
           return f.Active != nil && *f.Active == true
       }
    
  7. スライスをフィルタリング
       func filterPositive(numbers []int) []int {
           var result []int
           for _, n := range numbers {
               if n > 0 {
                   result = append(result, n)
               }
           }
           return result
       }
       
       nums := []int{-2, 5, 0, -1, 10}
       positiveOnly := filterPositive(nums) // [5, 10]
    
  8. デフォルト値の設定
       type Config struct {
           EnableLogs bool
           Verbose    bool
       }
       
       // デフォルト値を設定する関数
       func DefaultConfig() Config {
           return Config{
               EnableLogs: true, // デフォルトで有効
               Verbose:    false,
           }
       }
    
  9. 反射での扱い
       import "reflect"
       
       func isTrueValue(v interface{}) bool {
           rv := reflect.ValueOf(v)
           
           if rv.Kind() == reflect.Bool {
               return rv.Bool() == true
           }
           
           return false
       }
    

Goにおけるtrueは、シンプルながらも多くの文脈で使用される基本的な値です。特に条件分岐やフラグとしての使用が一般的であり、型の安全性を維持するためにGoでは他の型との暗黙的な変換が許可されていないことが重要な特徴です。