iterator

package
v0.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 6, 2026 License: MIT Imports: 0 Imported by: 0

Documentation

Overview

Package iterator 提供 Option 与 Result 使用的小型值迭代器。

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Iterator

type Iterator[T any] struct {
	// contains filtered or unexported fields
}

Iterator 表示一个不可变、可重复使用的有限序列迭代器。

func Empty

func Empty[T any]() Iterator[T]

Empty 创建一个空迭代器。

Example
package main

import (
	"fmt"

	"github.com/23jdd/gomad/iterator"
)

func main() {
	fmt.Println(iterator.Empty[int]().Len())
}
Output:
0

func FromSlice

func FromSlice[T any](values []T) Iterator[T]

FromSlice 基于 values 的副本创建迭代器。

Example
package main

import (
	"fmt"

	"github.com/23jdd/gomad/iterator"
)

func main() {
	values := []int{1, 2}
	iter := iterator.FromSlice(values)
	values[0] = 9
	fmt.Println(iter.Collect())
}
Output:
[1 2]

func Map

func Map[T, U any](iter Iterator[T], transform func(T) U) Iterator[U]

Map 转换每个元素,并允许改变元素类型。

Example
package main

import (
	"fmt"
	"strconv"

	"github.com/23jdd/gomad/iterator"
)

func main() {
	iter := iterator.Map(iterator.FromSlice([]int{1, 2}), strconv.Itoa)
	fmt.Println(iter.Collect())
}
Output:
[1 2]

func Once

func Once[T any](value T) Iterator[T]

Once 创建一个只包含 value 的迭代器。

Example
package main

import (
	"fmt"

	"github.com/23jdd/gomad/iterator"
)

func main() {
	fmt.Println(iterator.Once(10).Collect())
}
Output:
[10]

func (Iterator[T]) Collect

func (iter Iterator[T]) Collect() []T

Collect 返回序列的副本。

Example
package main

import (
	"fmt"

	"github.com/23jdd/gomad/iterator"
)

func main() {
	fmt.Println(iterator.Once(10).Collect())
}
Output:
[10]

func (Iterator[T]) Filter

func (iter Iterator[T]) Filter(predicate func(T) bool) Iterator[T]

Filter 仅保留 predicate 接受的元素。

Example
package main

import (
	"fmt"

	"github.com/23jdd/gomad/iterator"
)

func main() {
	iter := iterator.FromSlice([]int{1, 2, 3}).Filter(func(value int) bool {
		return value%2 == 1
	})
	fmt.Println(iter.Collect())
}
Output:
[1 3]

func (Iterator[T]) Len

func (iter Iterator[T]) Len() int

Len 返回迭代器中的元素数量。

Example
package main

import (
	"fmt"

	"github.com/23jdd/gomad/iterator"
)

func main() {
	fmt.Println(iterator.FromSlice([]int{1, 2}).Len())
}
Output:
2

func (Iterator[T]) Map

func (iter Iterator[T]) Map[U any](transform func(T) U) Iterator[U]

Map 转换每个元素,并允许改变元素类型。

Example
package main

import (
	"fmt"
	"strconv"

	"github.com/23jdd/gomad/iterator"
)

func main() {
	iter := iterator.FromSlice([]int{1, 2}).Map(strconv.Itoa)
	fmt.Println(iter.Collect())
}
Output:
[1 2]

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL