If you want the least amount of work, then use (similar to what OP
suggests), fmt.Sprint(x), the downside is that it is does far more work as
it makes a new string each time. The upside is that it should handle most
types (including numeric types). Alternatively, if the only thing you are
going to do is hand it to a fmt.* or log.* function, you could just leave
it as an interface{} and let the function you call "stringify" it for
you: http://play.golang.org/p/Ygq9nD75PF

Otherwise, if maximizing speed or minimizing string creation is important
than you can use type switches / type assertions and / or reflect. Here
I've created a toString method which, if possible, uses a method / feature
of the type to avoid the extra work and the extra string conversion that
fmt.SPrint* functions have to do. http://play.golang.org/p/fHs2ABo1c0

Also, there's an additional advantage that I can write custom string
representations for types I don't have the ability to modify (see time.Time

On Tuesday, January 29, 2013 5:19:40 PM UTC-8, david wrote:

can you relove this problem?I have encountered this problem.
On Tuesday, November 23, 2010 8:55:32 PM UTC+8, chris dollin wrote:
On 23 November 2010 12:39, Andreas Otto wrote:

my problem is that the only way to convert an "interface{}",
using a "unknown" type, into an "string" is (as I know)

fmt.Sprintf("%s", ifc)

Is this right, or can I test for an "string" like interface?
You can use a type test. If X is your interface{} variable and T is
the type you want to test for -- be it an interface type or a concrete
type -- then

aT, isT := X.(T)

will set isT to true iff X has underlying type T and aT to the
T value (the zero value if isT = false).
what is the standard in GO if something support a serialization into a
"string" object
fmt.Stringer looks like the plausible candidate.

Are you really sure you want to be doing this test? (You can test an
interface{} for equality against a string anyway ..)


Chris "allusive" Dollin
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Search Discussions

Discussion Posts


Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 4 of 5 | next ›
Discussion Overview
groupgolang-nuts @
postedJan 30, '13 at 1:39a
activeFeb 1, '13 at 4:33p



site design / logo © 2021 Grokbase