Background
Getting fancy with Go.
Will like to return a structure from a function.
Error
Error – Image
Error – Text
>go run return.Reference.user.User.undeclared.go # command-line-arguments .\return.Reference.user.User.undeclared.go:37:2: too many arguments to return have (*user.User) want () .\return.Reference.user.User.undeclared.go:49:25: getUserCurrent() used as value >
Explanation
- Error
- Reads
- too many arguments to return
have (*user.User)
want ()
.\return.Reference.user.User.undeclared.go:49:25: getUserCurrent() used as value
- too many arguments to return
- Reads
- Explanation
- Function returns user.User
- But, it is declared as returning zero parameters
Code
Original
package main import ( "fmt" "os/user" ) func getUserCurrent() { /* Declare Variables objUser as pointer (*) to user.User */ var objUser *user.User var strBuffer string var objError error /* Get current user by accessing the user object https://golang.org/pkg/os/user/ Imported Module os/user */ objUser, objError = user.Current() if objError!= nil { strBuffer = fmt.Sprintf( "Failed to properly access the %s module\n. The error is %s", "user.Current", objError) fmt.Println(strBuffer); panic(objError) } return (objUser) } func main(){ var objUser *user.User var strBuffer string objUser = nil objUser= getUserCurrent() if (objUser != nil){ strBuffer = fmt.Sprintf( "Current User is %s \n", objUser.Username) fmt.Println(strBuffer); } objUser = nil }
Revised
package main import ( "fmt" "os/user" ) /* Function Name:- getUserCurrent Returns:- *user.User Parameters:- None */ func getUserCurrent() *user.User{ /* Declare Variables objUser as pointer (*) to user.User */ var objUser *user.User var strBuffer string var objError error /* Get current user by accessing the user object https://golang.org/pkg/os/user/ Imported Module os/user */ objUser, objError = user.Current() if objError!= nil { strBuffer = fmt.Sprintf( "Failed to properly access the %s module\n. The error is %s", "user.Current", objError) fmt.Println(strBuffer); panic(objError) } // return objUser return (objUser) } func main(){ var objUser *user.User var strBuffer string objUser = nil /* Calls:- getUserCurrent returns:- objUser Parameters :- none */ objUser= getUserCurrent() /* If returned is not null, display username */ if (objUser != nil){ strBuffer = fmt.Sprintf( "Current User is %s \n", objUser.Username) fmt.Println(strBuffer); } // null out reference objUser = nil }
Source Code Control
Github
- Repository
Summary
There is a bit of difference in how the return types are indicated in GoLang compared to languages that I am familiar with.
In C, C++, C#, and VB, the return types are indicated to the left of the function.
Whereas, in Go the return type is declared to the right of the function.