Goktug Hatipoglu
Goktug Hatipoglu

Reputation: 143

Exported functions from another package

I am following instructions in https://golang.org/doc/code.html#Workspaces link and I build my first Go program.

So, I tried to make library with this instruction = https://golang.org/doc/code.html#Library

and everything is perfect until building hello.go, its gives me this error.

/hello.go:10:13: undefined: stringutil.Reverse

I've already rebuild my reverse.go.

Thats my code:

package main

import (
    "fmt"

    "github.com/d35k/stringutil"
)

func main() {
    fmt.Printf(stringutil.Reverse("!oG ,olleH"))
}

that's my reverse.go (same as docs)

package stringutil

func reverse(s string) string {
    r := []rune(s)
    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
        r[i], r[j] = r[j], r[i]
    }
    return string(r)
}

and my gopath variable

export GOPATH=$HOME/GoLang

and my files ar in

GoLang/src/github.com/mygithubusername/

Upvotes: 10

Views: 10711

Answers (2)

Thiemo
Thiemo

Reputation: 390

A different problem with the same symptoms I ran into was that I was having two functions with the same name in Package B. Since two functions wih the same name but different types are no problem, I didn't think about it too much, however, VSCode didn't show the methods when I tried to use them in Package A, despite them being capitalized.

According to the question asked here this is not supported by Go and requires you to change the function name or use introspection/an interface.

Thought I'd share it since googling brought me to this question here multiple times and it might be something other Go learners might run into as well...

Upvotes: 0

Himanshu
Himanshu

Reputation: 12685

Golang Tour specify exported name as

A name is exported if it begins with a capital letter. And When importing a package, you can refer only to its exported names. Any "unexported" names are not accessible from outside the package.

Change the name of reverse func to Reverse to make it exportable to main package. Like below

package stringutil

func Reverse(s string) string {
    r := []rune(s)
    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
        r[i], r[j] = r[j], r[i]
    }
    return string(r)
} 

Upvotes: 23

Related Questions