1

This example will be a little bare to strip out the custom xml parsing that I'm doing, but I've run into this issue:

package main

import (
    "encoding/xml"
    "fmt"
)

type Foo string

func main() {
    var f Foo
    var b string

    c := xml.CharData{}
    f = string(c)
    b = string(c)
    fmt.Println(b)
}
//prog.go:15: cannot use string(c) (type string) as type Foo in assignment

Foo is a type of string, what am I missing to convert the string representation of xml.CharData (which is valid, use it in many decoders) to a custom type which is a string?

1 Answer 1

4

Convert c to Foo directly.

f = Foo(c)

Playground: http://play.golang.org/p/WR7gCHm9El

Edit: This works because Foo is a string underneath. Foo is a new and distinct derived type; its base type is string. You can similarly make derived types for any existing type. Each derived type is distinct, so you get type safety. Conversions must be explicit.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.