Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import "fmt"
- type IPAddr [4]byte
- // TODO: Add a "String() string" method to IPAddr.
- func (ip IPAddr) String() string {
- rs := ""
- for k, v := range ip {
- if k == 0 {
- rs += fmt.Sprintf("%v", v)
- continue
- }
- rs += fmt.Sprintf(".%v", v)
- }
- return rs
- }
- func main() {
- hosts := map[string]IPAddr{
- "loopback": {127, 0, 0, 1},
- "googleDNS": {8, 8, 8, 8},
- }
- for name, ip := range hosts {
- fmt.Printf("%v: %vn", name, ip)
- }
- }
- package main
- import "fmt"
- type IPAddr [4]byte
- // TODO: Add a "String() string" method to IPAddr.
- func (ip IPAddr) String() string {
- return fmt.Sprintf("%v.%v.%v.%v", ip[0], ip[1], ip[2], ip[3])
- }
- func main() {
- hosts := map[string]IPAddr{
- "loopback": {127, 0, 0, 1},
- "googleDNS": {8, 8, 8, 8},
- }
- for name, ip := range hosts {
- fmt.Printf("%v: %vn", name, ip)
- }
- }
- package main
- import (
- "fmt"
- "net"
- )
- type IPAddr [4]byte
- func (ip IPAddr) String() string {
- return net.IP(ip[:]).String()
- }
- func main() {
- hosts := map[string]IPAddr{
- "loopback": {127, 0, 0, 1},
- "googleDNS": {8, 8, 8, 8},
- }
- for name, ip := range hosts {
- fmt.Printf("%v: %vn", name, ip)
- }
- }
- loopback: 127.0.0.1
- googleDNS: 8.8.8.8
- package main
- import (
- "fmt"
- "strconv"
- )
- type IPAddr [4]byte
- func (ip IPAddr) String() string {
- s := make([]byte, 0, (1+3)*len(IPAddr{}))
- for i, b := range ip {
- if i > 0 {
- s = append(s, ',')
- }
- s = strconv.AppendInt(s, int64(b), 10)
- }
- return string(s)
- }
- func main() {
- hosts := map[string]IPAddr{
- "loopback": {127, 0, 0, 1},
- "googleDNS": {8, 8, 8, 8},
- }
- for name, ip := range hosts {
- fmt.Printf("%v: %vn", name, ip)
- }
- }
- loopback: 127,0,0,1
- googleDNS: 8,8,8,8
- package main
- import (
- "fmt"
- "testing"
- )
- type IPAddr [4]byte
- func (ip IPAddr) String() string {
- rs := ""
- for k, v := range ip {
- if k == 0 {
- rs += fmt.Sprintf("%v", v)
- continue
- }
- rs += fmt.Sprintf(".%v", v)
- }
- return rs
- }
- func BenchmarkString1(b *testing.B) {
- hosts := map[string]IPAddr{
- "loopback": {127, 0, 0, 1},
- "googleDNS": {8, 8, 8, 8},
- }
- for N := 0; N < b.N; N++ {
- for name, ip := range hosts {
- fmt.Sprintf("%v: %vn", name, ip)
- }
- }
- }
- BenchmarkString1-8 841730 1412 ns/op 176 B/op 19 allocs/op
- BenchmarkString2-8 1228399 931 ns/op 128 B/op 8 allocs/op
- BenchmarkString3-8 1984806 574 ns/op 128 B/op 8 allocs/op
- BenchmarkString4-8 1765022 626 ns/op 128 B/op 8 allocs/op
- func (ip IPAddr) String() string {
- return fmt.Sprintf("%v.%v.%v.%v", ip[0], ip[1], ip[2], ip[3])
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement