Command line arguments based on index.
//repeatgreetings 108 //repeatgreetings 108 | wc -l package main import ( "fmt" "log" "os" "strconv" ) func main() { var repeatCount int var err error if len(os.Args) >= 2 { repeatCount, err = strconv.Atoi(os.Args[1]) if err != nil { log.Fatal(err) } for i := 0; i < repeatCount; i++ { fmt.Println("Hello Gopher!") } } }
Command line flags which uses keynames instead of index
//personalgreetings -help //personalgreetings //personalgreetings -gophername Uday package main import ( "flag" "fmt" ) func main() { var gopherName string //Arguments: variable,flag,default value,description flag.StringVar(&gopherName, "gophername", "Gopher", "The name of the Gopher") flag.Parse() fmt.Println("Hello " + gopherName + "!") }
Case study: username checker
//usernamechecker -username ^Java_Duke^ //usernamechecker -username @Uday package main import ( "flag" "fmt" "log" "regexp" ) const UsernameRegex string = `^@?(\w){1,15}$` //backticks instead of double/single quotes. func main(){ var usernameInput string flag.StringVar(&usernameInput,"username","Gopher","The GopherFace Username to Check") flag.Parse() fmt.Println("GopherFace Username Validation Checker") fmt.Println("Checking Syntax for username,\"",usernameInput,"\",resulted in: ",CheckUsernameSyntax(usernameInput),"\n") } func CheckUsernameSyntax(username string)bool{ validtionResult := false r,err:=regexp.Compile(UsernameRegex) if err!=nil{ log.Fatal(err) } validtionResult=r.MatchString(username) return validtionResult }
No comments:
Post a Comment