Standard library / os

os.Expand()

Replaces $name and ${name} using a caller-supplied lookup function. It is not shell evaluation. Example intended for Linux/AMD64 with Go 1.23.2 in a disposable working directory; other platforms may differ. Expected stdout: 'Hello Go\n'.

Formal Syntax & Structure

go syntaxgo
func Expand(s string, mapping func(string) string) string

Parameters & Attributes

NameTypeDescription
sstringText containing variable references.
mappingfunc(string) stringFunction mapping variable names to replacement strings.

Return Value

string

Replaces $name and ${name} using a caller-supplied lookup function.

Working Example

Example Snippetgo
package main
import (  "fmt"  "os")
func must(e error) {  if e != nil {    panic(e)  }}func main() {  fmt.Println(os.Expand("Hello $NAME", func(k string) string { return map[string]string{"NAME": "Go"}[k] }))}
Go Reference