Cannot refer to unexported name and undefined Error in Go

Are you facing unexported and undefined errors in Go programming language like the following ?

.\main.go:9:2: cannot refer to unexported name goresty.getResponseResty
.\main.go:9:2: undefined: goresty.getResponseResty
Unexported name error:

Let us say you have the following project structure and facing the above error while importing custom packages and using functions in that package

src
|-gosneppets
|  |-main.go
|--|-goresty
|    |-resty.go
package main

import (
	goresty "gosneppets/goresty"
)

func main() {

	goresty.getResponseResty()
}
package goresty

import (
	"fmt"
	"gopkg.in/resty.v1"
)

func getResponseResty() {
	resp, err := resty.R().Get("https://httpbin.org/get")

	// explore response object
	fmt.Printf("\nError: %v", err)
	fmt.Printf("\nResponse Status Code: %v", resp.StatusCode())
	fmt.Printf("\nResponse Status: %v", resp.Status())
	fmt.Printf("\nResponse Time: %v", resp.Time())
	fmt.Printf("\nResponse Received At: %v", resp.ReceivedAt())
	fmt.Printf("\nResponse Body: %v", resp)
}
Note: Identifier Access

One of the important feature that you need to know in Go language is to use an uppercase or lowercase letter as a first letter when we name a type or variable or function so that the identifier would be public and any code in any package could use it.

If the first letter is lowercase, then the identifier is private and could only accessed within the package where it is declared.

Solution for Unexported name and Undefined Error:
  • You should make your function exportable with an uppercase like func GetResponseResty()  instead of func getResponseResty() .
  • And call the function like goresty.GetResponseResty()  in the main.go  in the main function.
Subscribe
Notify of
guest

6 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Luella James
Luella James
5 years ago

Good Stuff. This is really a tremendous website.

Pavan
Pavan
4 years ago

this was bugging me since morning, Thanks a lot

Michael Bugaevski
Michael Bugaevski
3 years ago

Thank you very much. I am new to GO, and I completely forgot the “uppercase”…
I have been hitting the wall for 2 weeks. Now [Note: Identifier Access] – fixed my issue.
Thanks again.
Michael.

shravs
shravs
2 years ago

Thank you soo much… after reading your comment i also fixed my issue of that capital case

Rakesh Gupta
Rakesh Gupta
3 years ago

Great insight!

topo
topo
3 years ago

Hello, just came across your articles, really appreciate your works!