Open rodriggj opened 2 years ago
go build ...
commandIf you want to use a persistent version of the running program you need to use the go build ...
vs. the go run...
command.
Run the following command with our main file and see the difference.
go build -o greeter
ERROR: In the lesson, the instructor was able to just run this command, but when I tried I had to first run
go mod init example.com/go-demo-2
which created ago.mod
file. Then I was able to rungo build -o greeter
which created agreeter
file without the go extension. I was then able to run./greeter
and see the contents of theArgs[]
slice. The contents showed what was presented in the lesson so it ultimately worked, just needed the additional steps.
Args[]
you can add variables to the slice in positions Args[1], Args[2], etc. To do this at the command line write the following code.
./greeter "hey" "ho" "howdy"
Results in ...
fmt.Println()
function. Modify the main.go script as follows:
package main
import ( "fmt" "os" )
func main() { fmt.Printf("%#v\n", os.Args)
fmt.Println("Path:", os.Args[0])
fmt.Println("1st Argument:", os.Args[1])
fmt.Println("2nd Argument:", os.Args[2])
fmt.Println("3rd Argument:", os.Args[3])
fmt.Println("Number of items inside os.Args:", len(os.Args))
}
> **NOTE:** The last line of this example use the `len()` function which takes a data structure like a slice and returns the quantity of items within the data structure you pass in. In this case it will return the "length" of the os.Args slice.
2. To run this program you have to re-build the program so run the following:
```go
go build -o greeter
ERROR: In the video the instuctor simply runs
go build -o greeter
after re-building and the output to the terminal shows correctly. That was not my experience. The process I had to take was 1. make the modifications to themain.go
prgoram 2. rebuild the program withgo build -o greeter
command at the terminal 3. I ran themain.go
program withgo run main.go
after re-building and received a "out-of-bounds" error message. This is because since rebuilding the program you have to re-input the strings you want stored in the array. So 4. execute the./greeter "hey" "ho" "howdy"
commands in the terminal. 5. run thego run main.go
command and everything works.
Results in ...
View basics of os.Args
import ( "fmt" "os" )
func main() { fmt.Printf("%#v\n", os.Args) }
Results in ...