Hi, I have the following code fragment:package mainimport("fmt""strconv")func convert(val interface{}, text string) {switch t := val.(type) {case *float32:v, err := strconv.ParseFloat(text, 32)if err == nil {*t = float32(v)}default:panic("Unknown type")}}func main(){var f float64convert(&f,"345.344")fmt.Println(f)}I want if I supply wrong type to `convert`, compiler to tell me, instead waiting for runtime panic.Is there any way?
Yes, there will be other types. I used float32 only for simplicity.Runtime is not good. It takes away possibilities to catch errors early.Does anyone proposed it to Google (I guess at expense of another keyword)?
Hi, I have the following code fragment:
package mainimport("fmt""strconv")func convert(val interface{}, text string) {switch t := val.(type) {case *float32:v, err := strconv.ParseFloat(text, 32)if err == nil {*t = float32(v)}default:panic("Unknown type")}}func main(){var f float64convert(&f,"345.344")fmt.Println(f)}
I want if I supply wrong type to `convert`, compiler to tell me, instead waiting for runtime panic.
Is there any way?
package mainimport("fmt""strconv")
type Float32 float32type Float64 float64type TypeConverter interface {typeConvert(text string)}func (f *Float32) typeConvert(text string) {
v, err := strconv.ParseFloat(text, 32)if err == nil {
*f = Float32(v)}}func convert(val TypeConverter, text string) {val.typeConvert(text)}func main() {{var f Float32convert(&f,"345.344")fmt.Println(f)}}Changing Float32 for Float64, gives compile time error:./goplay.go:29: cannot use &f (type *Float64) as type TypeConverter in function argument:
*Float64 does not implement TypeConverter (missing typeConvert method)
09 май 2013, четвъртък, 15:10:57 UTC+3, drago....@gmail.com написа:
Hi, I have the following code fragment:
package mainimport("fmt""strconv")func convert(val interface{}, text string) {switch t := val.(type) {case *float32:v, err := strconv.ParseFloat(text, 32)if err == nil {*t = float32(v)}default:panic("Unknown type")}}func main(){var f float64convert(&f,"345.344")fmt.Println(f)}
I want if I supply wrong type to `convert`, compiler to tell me, instead waiting for runtime panic.
Is there any way?