liveBook · Manning

String

As explained in Go by Example

A Go string is an immutable sequence of bytes whose contents can be represented without copying when sliced.

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

How Go by Example covers it

How deep it goes
Demonstrates string fields, formatted reconstruction, interface requirements, and tests, but does not examine string representation internals.
Examples
Shows URL components, formatted URL reconstruction, String method tests, and flag value parsers.
What it assumes
Assumes familiarity with structs, pointers, methods, formatted output, interfaces, and basic Go testing.
What you can do after
Build it from scratch by adding String methods, testing their output, and satisfying the flag.Value interface.
How it connects
Connects strings with structs, methods, URL parsing, interfaces, command-line flags, and testing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go by Example. The section links point to the parts of the book it draws on.