Generics code help

This code below gives the following error. Any thoughts on what I am doing wrong?

./main.go:22:20: cannot convert *val (variable of type parameter T constrained by StringType) to string
./main.go:23:18: cannot convert strings.TrimSpace(str) (value of type string) to T
package main

import "strings"

func main() {
	var msg = "Hello"
	var _ = NewStringField(&msg)
}

type StringType interface {
	~string
}

type StringField[T StringType] struct {
	val *T
}

func NewStringField[T StringType](val *T) *StringField[T] {
	if  val == nil {
    return nil
  }
  var str = string(*val)
  var newVal = T(strings.TrimSpace(str))

  return &StringField[T]{
		val: &newVal,
	}
}

I tried copying and pasting your code into the Go 2 playground but got an error:

prog.go:11:2: illegal character U+007E '~'

Can you confirm that the code you uploaded is the code you’re testing with and if it is, can you provide the steps you’re following to build it?

I think the go2go playground is no longer in sync with latest generics proposals. I am using golang master branch.

Sorry, I don’t use Go 2. Maybe someone else here can help you.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.