liveBook · Manning

String

As explained in Learn Go with Pocket-Sized Projects

A string is a Go value type representing a sequence of bytes, conventionally used for textual data.

A string is a Go value type representing a sequence of bytes, conventionally used for textual data. Functions can return strings, accept them as parameters, and store their results for later printing or testing. section 2.1.3 section 2.2.1

Common uses include:

  • Returning generated text from a function, such as a greeting. section 2.1.3
  • Representing a language code or description through a named string type, such as language. section 2.2.1
  • Implementing Stringer with a String() string method so fmt.Printf can print a value using string-oriented verbs. section 5.2.1
  • Building larger output from repeated string fragments with strings.Builder instead of naive concatenation. section 5.2.1

Language-specific greetings

Define type language string, accept it in greet, and use a switch to return "Hello world" for "en" or "Bonjour le monde" for "fr". The caller passes "en", stores the returned string, and prints it. section 2.2.1

Listing 2.6 main.go: Adding a new language
package main

import "fmt"

func main() {
    greeting := greet("en")
    fmt.Println(greeting)
}

// language represents the language's code
type language string #1

// greet says hello to the world in the specified language
func greet(l language) string {
    switch l { #2
    case "en":
        return "Hello world"
    case "fr":
        return "Bonjour le monde"
    default:
        return ""
    }
}

Runnable code combining a named string type, a string-returning function, a language switch, and a main function that prints the result. section 2.2.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains string returns, parameters, named string types, Stringer, and concatenation, but does not descend into byte-level operations.
Examples
Demonstrates greetings, language codes, emoji-based hints, feedback slices, naive concatenation, and strings.Builder.
What you can do after
Build and refactor functions that return strings, pass named string values, implement Stringer, and assemble formatted output.
How it connects
Connects strings with named types, switch statements, interfaces, fmt.Printf, and strings.Builder.

Also explained in

Compare how 24 books explain string →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.