遍历传入泛型的 []rune | string。

huangapple go评论91阅读模式
英文:

Iterate over a []rune | string passed in generics

问题

我正在使用这个约束规则来处理泛型:

type LineParser[T []rune | string] struct {
}

我有这个结构体的泛型方法:

func (it *LineParser[T]) Parser(line T)

在这个方法内部,我想要迭代这个行,但是我得到了这个错误:

> invalid operation: cannot slice line (variable of type T constrained by []rune|string): T has no core type

有什么建议吗?

英文:

I am working with generics with this constrained rule:

type LineParser[T []rune | string] struct {
}

And I have this generic method of that struct:

func (it *LineParser[T]) Parser(line T)

Inside of that method I want to iterate the line but I am getting this error:

> invalid operation: cannot slice line (variable of type T constrained by []rune|string): T has no core type

any suggestions?

答案1

得分: 3

line值转换为[]rune值后再进行迭代。这样,方法的每个实例都将迭代相同类型的值。

type LineParser[T []rune | string] struct {}

func (it *LineParser[T]) Parser(line T) {
	for _, r := range []rune(line) {
		// 对下一个rune执行某些操作
		_ = r
	}
}
英文:

Convert the line value to a []rune value before iterating. This way, every instance of the method will iterate over the same type.

type LineParser[T []rune | string] struct {}

func (it *LineParser[T]) Parser(line T) {
	for _, r := range []rune(line) {
		// do something with the next rune
		_ = r
	}
}

huangapple
  • 本文由 发表于 2022年12月6日 08:01:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/74695772.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定