Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over a []rune | string passed in generics

Tags:

generics

go

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?

like image 383
Fernando González Avatar asked Oct 26 '25 15:10

Fernando González


1 Answers

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
    }
}
like image 172
Hymns For Disco Avatar answered Oct 29 '25 07:10

Hymns For Disco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!