Golang os.Expand() Function with Examples

Golang | os.Expand() Function: Here, we are going to learn about the Expand() function of the os package with its usages, syntax, and examples.
Submitted by IncludeHelp, on November 16, 2021

os.Expand()

In the Go language, the os package provides a platform-independent interface to operating system (Unix-like) functionality. The Expand() function is an inbuilt function of the os package, it is used to replace ${var} or $var in the string based on the mapping function. For example, os.ExpandEnv(s) is equivalent to os.Expand(s, os.Getenv).

It accepts two parameters (s string, mapping func(string) string), one is the string and the second one is the mapping function and returns the string.

Syntax:

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

Parameter(s):

  • s - String
  • mapping - Mapping function

Return Value:

The return type of the os.Expand() function is a string, it returns a string replaced the $var with the corresponding value.

Example 1:

// Golang program to demonstrate the
// example of Expand() function

package main

import (
	"fmt"
	"os"
)

func main() {
	mapperfunc := func(value string) string {
		switch value {
		case "GM_MSG":
			return "Good Morning!"
		case "CUSTOMER_NAME":
			return "Alex"
		}

		return ""
	}

	fmt.Println(os.Expand("Hey, ${GM_MSG}, $CUSTOMER_NAME!", mapperfunc))
	fmt.Println(os.Expand("Hi, $GM_MSG, $CUSTOMER_NAME!", mapperfunc))
}

Output:

Hey, Good Morning!, Alex!
Hi, Good Morning!, Alex!

Example 2:

// Golang program to demonstrate the
// example of Expand() function

package main

import (
	"fmt"
	"os"
)

func main() {
	// Setting customize environment
	os.Setenv("NAME", "Alvin")
	os.Setenv("DIRPATH", "/usr/Alvin")
	// Getting environment
	str := os.ExpandEnv("$NAME and Directory path $DIRPATH.")
	fmt.Println(str)

	// Getting environment
	str = os.ExpandEnv("$NAME, $PATH, $HOME")
	fmt.Println(str)
}

Output:

Alvin and Directory path /usr/Alvin.
Alvin, /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin, /root

Golang os Package »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.