1
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?

package main

import (
    "fmt"
)

func Later() func(string) string {
    var history []string  // 履歴を保持するスライス
    var currentIndex int // 現在の位置を追跡
    
    return func(next string) string {
        // 新しい値が空でない場合、履歴に追加
        if next != "" {
            history = append(history, next)
            currentIndex = len(history) - 1
        }
        
        // 履歴が空の場合、空文字列を返す
        if len(history) == 0 {
            return ""
        }
        
        // 現在の位置の値を返す
        return history[currentIndex]
    }
}

func main() {
    f := Later()
    
    // 基本的な使用例
    fmt.Println(f("Hello"))   // Hello
    fmt.Println(f("World"))   // World
    
    // 空文字列を渡すと現在の値が返される
    fmt.Println(f(""))       // World
    
    // 新しい値を追加
    fmt.Println(f("Go"))     // Go
    
    // 再び空文字列を渡すと最後の値が返される
    fmt.Println(f(""))      // Go
}
  • currentIndex は履歴内の現在位置を指し示します(0から始まるインデックス)
  • 空文字列("")を渡すと、新しい値は追加せずに現在の値が返されます
  • history スライスは新しい値が追加されるたびに自動的に拡張されます

クロージャーの構造

func Later() func(string) string {
   var history []string      // 履歴を保持するスライス
   var currentIndex int     // 現在の位置を追跡
   
   return func(next string) string {
       // 新しい値が空でない場合、履歴に追加
       if next != "" {
           history = append(history, next)
           currentIndex = len(history) - 1
       }
       
       // 履歴が空の場合、空文字列を返す
       if len(history) == 0 {
           return ""
       }
       
       // 現在の位置の値を返す
       return history[currentIndex]
   }
}

主要な特徴- 複数の変数(historycurrentIndex)をクロージャー内で管理

  • 状態の永続化と操作機能を提供
  • より実用的なユースケースに対応可能

状態管理の仕組み- history: 文字列の履歴を保持するスライス

  • currentIndex: 現在参照中の履歴の位置を追跡
  • 新しい値の追加時に自動的に更新

実用的な応用例- コマンドヒストリーの実装

  • バックアップシステムの作成
  • ステートマシンの実装

拡張性この基本構造を基に、以下のような機能を追加できます:

  • 履歴の最大サイズ制限
  • 履歴の検索機能
  • 状態の永続化(ファイル保存など)

このようなクロージャーによる実装は、データのカプセル化と状態管理を効果的に行うことができます。

1
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
1
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?