ADVERTISEMENT
ADVERTISEMENT

Golang os.ExpandEnv() Function with Examples

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

os.ExpandEnv()

In the Go language, the os package provides a platform-independent interface to operating system (Unix-like) functionality. The ExpandEnv() function is an inbuilt function of the os package, it is used to replace ${var} or $var in the string according to the values of the current environment variables, undefined variables are replaced by the empty string.

It accepts one parameter (s string) and returns a string replaced the $var with the corresponding value.

Syntax:

func ExpandEnv(s string) string

Parameter(s):

  • s - String

Return Value:

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

Example 1:

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

package main

import (
	"fmt"
	"os"
)

func main() {
	os.Setenv("GM_MSG", "Good Morning!")
	os.Setenv("CUSTOMER_NAME", "Alex")

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

Output:

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

Example 2:

// Golang program to demonstrate the
// example of ExpandEnv() 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.