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























