英文:
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
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论