Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exported functions from another package

Tags:

go

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/
like image 326
Goktug Hatipoglu Avatar asked Apr 28 '18 18:04

Goktug Hatipoglu


People also ask

How do you call a function from another package?

You should prefix your import in main.go with: MyProj , because, the directory the code resides in is a package name by default in Go whether you're calling it main or not. It will be named as MyProj . package main just denotes that this file has an executable command which contains func main() .

What is package go?

Go programs are organized into packages. A package is a collection of source files in the same directory that are compiled together. Functions, types, variables, and constants defined in one source file are visible to all other source files within the same package. A repository contains one or more modules.


1 Answers

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)
} 
like image 50
Himanshu Avatar answered Nov 12 '22 20:11

Himanshu