ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.