On Mon, 20 Apr 2015 11:33:09 +1000
simran <
simran...@gmail.com> wrote:
> Where can one find the definition of the string(...) function.
[...]
> * It will call a "String(...)" function if one exists for that
> object/struct?
In additions to what others have said, this one works in Go the other
way round: the code receiving arbitrary values, which it intends to get
a textual representation of, might "type-assert" the value to an
interface which supports a method of getting that textual
representation.
For instance, the `fmt` standard package implements this approach by
having the Stringer interface [1]. Then, the implementations of
various Print* functions in that package can do something along these
lines:
func PrintAny(v interface{}) {
var s string
switch v.(type) {
case string:
s = v
case Stringer:
// OK, we can ask the value in `v` to give us its
// textual representation as its type sees fit, as it
// supports the `func String() string` method:
s = v.String()
default:
// Well, then use reflection to produce the textual
// representation of the value in `v`.
}
// Output whatever ended up in `s`.
}
All this is explained in detail in [2], which, I'd say, is a must-read
(in its entirety) for any newfangled gopher.
[...]
1.
https://golang.org/pkg/fmt/#Stringer
2.
https://golang.org/doc/effective_go.html#interface_conversions