zhanghao001122
zhanghao001122

Reputation: 13

String method for type IPAddr

package main

import (
    "fmt"
    "strings"
)

type IPAddr [4]byte

func (ip IPAddr) String() string {  
    return strings.Trim(strings.Join(strings.Fields(fmt.Sprint([4]byte(ip))), "."), "[]")
}

func main() {
    hosts := map[string]IPAddr{
        "loopback":  {127, 0, 0, 1},
        "googleDNS": {8, 8, 8, 8},
    }
    for name, ip := range hosts {
        fmt.Printf("%v: %v\n", name, ip)
    }
}

Q 1: I do not see any call made to String() method for type IPAddr but it' still getting called. Why?

Q 2: Why the name of the method must be String() and not Stringa(), Stringb()?

Upvotes: 0

Views: 198

Answers (2)

shmsr
shmsr

Reputation: 4204

type Stringer interface {
    String() string
}

Stringer is implemented by any value that has a String method, which defines the “native” format for that value. The String method is used to print values passed as an operand to any format that accepts a string or to an unformatted printer such as Print.

So when you define a String method for the type and pass the instance of that type to fmt.Printf and friends then it is converted to a value of type interface{} which you can see from the function signature, also. Then in fmt package, it checks if the String method for the type is defined (means that it implements the Stringer interface) and calls it.

So, I'd suggest that it you should read about interfaces, first.

Upvotes: 2

Shubham Srivastava
Shubham Srivastava

Reputation: 1877

  1. The string method is part of stringer interface package fmt looks for passed values to check if the input implements Stringer interface if it does it will automatically call the stringer function while printing

  2. Since it is based on a particular interface it need a fixed method signature to be invoked if it does not implement specific signature the fmt package will not call string method

you can read more at this here https://golang.org/pkg/fmt/#Stringer

Upvotes: 1

Related Questions