spf13 / cast

safe and easy casting from one type to another in Go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

'cast.ToString()' conversion error

wlynxg opened this issue · comments

A strange error occurs when I use toString. The example code is as follows:

package main

import (
	"fmt"
	"github.com/spf13/cast"
)
type NewString string

func main() {
	var test NewString
	test = "this is a test string"
	fmt.Println("original: ",test)
	fmt.Println("use string() func: ",string(test))
	fmt.Println("use cast.ToString() func: ",cast.ToString(test))
	fmt.Println(cast.ToString(test)=="")
}

Output:

original:  this is a test string
use string() func:  this is a test string
use cast.ToString() func:  
true

This is not a mistake, your custom type is obviously not equal to the base type.

This is not a mistake, your custom type is obviously not equal to the base type.

So what is a better way to use cast for custom types?

This is not a mistake, your custom type is obviously not equal to the base type.

So what is a better way to use cast for custom types?

First the custom type implements the String() string interface, and only then more processing is possible.