String appears both as a value type for storing URL components and as a method that converts a structured value back into readable text. A URL stores its Scheme, Host, and Path in string fields; its String method joins them with fmt.Sprintf. section 2.1.1
Reassembling a URL
A pointer receiver can implement String by returning fmt.Sprintf("%s://%s/%s", u.Scheme, u.Host, u.Path). A test then compares the result with "https://github.com/inancgumus" and reports mismatches with t.Errorf. section 2.1.1 section 2.3.1
String also supplies a common interface operation:
- The flag.Value interface requires String() string and Set(string) error. section 4.4.1
- Flag uses String to obtain a variable’s default value for later usage text. section 4.4.1
Listing 2.1 Implementing the url package (url/url.go)
package url
import "fmt"
// A URL represents a parsed URL.
type URL struct {
Scheme string
Host string
Path string
}
// Parse parses a URL string into a URL structure.
func Parse(rawURL string) (*URL, error) {
return &URL{ #1
Scheme: "https", #2
Host: "github.com", #2
Path: "inancgumus", #2
}, nil #3
}
// String reassembles the URL into a URL string.
func (u *URL) String() string { #4
return fmt.Sprintf("%s://%s/%s", u.Scheme, u.Host, u.Path)
}
Inspect the complete URL type, Parse function, and String method implementation. section 2.1.1
