×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

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

Parameters

  • 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 »




Comments and Discussions!

Load comments ↻





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