Why does VS Code display a working function as "undeclared name"? - go

I made a very simple Go program, showing the current time. The function gets loaded from another source file with the same package (main).
For some reason, VS Code thinks, the function has an undeclared name.
Here's the code:
main.go:
package main
import "fmt"
func main() {
fmt.Println("Hello World!")
displayTime()
fmt.Scanf("h")
}
show_time.go:
package main
import (
"fmt"
"time"
)
func displayTime() {
fmt.Println(time.Now())
}
It's in the same directory, and everything compiles right. It's just that red mark that won't go and would disturb me. Also, the red number gets added by 1, everytime I call a extern function..

Related

I can't import "cloud.google.com/go/datastore"

I can't understand why this :/
I tried go get -u ** with every url that I found.
Thanks
Golang:
$ go version
go version go1.13.3 windows/amd64
Source test:
package main
import (
"fmt"
"cloud.google.com/go/datastore"
)
var client *datastore.Client
func main() {
fmt.Println("Work")
}
Error:
$ go run main.go
# google.golang.org/grpc/internal/transport
..\..\..\..\google.golang.org\grpc\internal\transport\http_util.go:270:23: cannot use hf (type "vendor/golang.org/x/net/http2/hpack".HeaderField) as type
"golang.org/x/net/http2/hpack".HeaderField in argument to d.processHeaderField
..\..\..\..\google.golang.org\grpc\internal\transport\http_util.go:675:23: cannot use "golang.org/x/net/http2/hpack".NewDecoder(http2InitHeaderTableSize,
nil) (type *"golang.org/x/net/http2/hpack".Decoder) as type *"vendor/golang.org/x/net/http2/hpack".Decoder in assignment
Go requires you make use of any package that you import. In this case you are importing "cloud.google.com/go/datastore" but not doing anything with it. The global variable that you declared is also not being used. Since it seems you are just trying to test, so I would recommend you do something with it (atleast print it). Like-
package main
import (
"fmt"
"cloud.google.com/go/datastore"
)
var client *datastore.Client
func main() {
fmt.Println(client)
}

Why function in my package is not working

I have put a small code file in $GOPATH which is ~/go/src. Here I have made a folder mysrc and there I have kept a file mytest.go, which is as follows:
package mytest
import ("fmt")
func myfn(){
fmt.Println("My own fn")
}
I try to import above code with following file:
package main
import ("mysrc")
main(){
myfn()
}
When I try to run above file, I get error:
# command-line-arguments
./useMyfn.go:3:1: syntax error: non-declaration statement outside function body
Where is the problem and how can it be solved? Thanks for your help.
Edit: I corrected the main fn to func main() but now the errors are:
# command-line-arguments
./useMyfn.go:2:9: imported and not used: "mysrc" as mytest
./useMyfn.go:4:2: undefined: myfn
You need to do few things
I suggest to use a package name that the name is same with the folder name.
The myfn() function need to be exported. How to do it: simply set the first character of the function name to uppercase.
package mysrc // <-- 1
import (
"fmt"
)
func Myfn() { // <-- 2
fmt.Println("My own fn")
}
The func keyword is required before main() statement.
To access a function from other package, you need to write down the package name before the function name. In this context it'll be mysrc.Myfn().
package main
import (
"mysrc"
)
func main() { // <-- 3
mysrc.Myfn() // <-- 4
}

Random number issue in golang

This is the code I'm working with:
package main
import "fmt"
import "math/rand"
func main() {
code := rand.Intn(900000)
fmt.Println(code)
}
It always returns 698081. I don't understand, what the is problem?
https://play.golang.org/p/XisNbqCZls
Edit:
I tried rand.Seed
package main
import "fmt"
import "time"
import "math/rand"
func main() {
rand.Seed(time.Now().UnixNano())
code := rand.Intn(900000)
fmt.Println(code)
}
There is no change. Now it always returns 452000
https://play.golang.org/p/E_Wfm5tOdH
https://play.golang.org/p/aVWIN1Eb84
A couple of reasons why you'll see the same result in the playground
Golang playground will cache the results
The time in the playground always starts at the same time to make the playground deterministic.
Last but not least, the rand package default seed is 1 which will make the result deterministic. If you place a rand.Seed(time.Now().UnixNano()) you'll receive different results at each execution. Note that this won't work on the playground for the second reason above.

Call a function from another package in Go

I have two files main.go which is under package main, and another file with some functions in the package called functions.
My question is: How can I call a function from package main?
File 1: main.go (located in MyProj/main.go)
package main
import "fmt"
import "functions" // I dont have problem creating the reference here
func main(){
c:= functions.getValue() // <---- this is I want to do
}
File 2: functions.go (located in MyProj/functions/functions.go)
package functions
func getValue() string{
return "Hello from this another package"
}
You import the package by its import path, and reference all its exported symbols (those starting with a capital letter) through the package name, like so:
import "MyProj/functions"
functions.GetValue()
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(). Then, you can run this code as: go run main.go. See here for more info.
You should rename your func getValue() in functions package to func GetValue(), because, only that way the func will be visible to other packages. See here for more info.
File 1: main.go (located in MyProj/main.go)
package main
import (
"fmt"
"MyProj/functions"
)
func main(){
fmt.Println(functions.GetValue())
}
File 2: functions.go (located in MyProj/functions/functions.go)
package functions
// `getValue` should be `GetValue` to be exposed to other packages.
// It should start with a capital letter.
func GetValue() string{
return "Hello from this another package"
}
Export function getValue by making 1st character of function name capital, GetValue
you can write
import(
functions "./functions"
)
func main(){
c:= functions.getValue() <-
}
If you write in gopath write this import functions "MyProj/functions" or if you are working with Docker
In Go packages, all identifiers will be exported to other packages if the first letter of the identifier name starts with an uppercase letter.
=> change getValue() to GetValue()
you need to create a go.mod file in the root directory of your project: go mod init module_name
the name of exposed function should start with capital letter
import(
"module_name/functions"
)
func main(){
functions.SomeFunction()
}

Error in importing custom packages in Go Lang

I have created a library by the name libfastget which is in the src with my program as
src
|-libfastget
| |-libfastget.go
|
|-MainProgram
|-main.go
and the libfastget exports a funtion fastget as follows
package libfastget
import (
"fmt"
"io"
)
func fastget(urlPtr *string, nPtr *int, outFilePtr *string) download {
.....
return dl
}
When I use the library in my main program
package main
import (
"fmt"
"net/http"
"os"
"libfastget"
"path/filepath"
"strings"
"flag"
"time"
)
func uploadFunc(w http.ResponseWriter, r *http.Request) {
n:=libfastget.fastget(url,4,filename)
}
}
I get the following error upon trying to build with go build
# FServe
./main.go:94: cannot refer to unexported name libfastget.fastget
./main.go:94: undefined: libfastget.fastget
The strange thing is that the library file libfastget.a is present in the pkg folder.
you would need to make your function exportable with an uppercase for its name:
func Fastget(...
Used as:
n:=libfastget.Fastget(url,4,filename)
The spec mentions: "Exported identifiers":
An identifier may be exported to permit access to it from another package. An identifier is exported if both:
the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and
the identifier is declared in the package block or it is a field name or method name.
All other identifiers are not exported.
to export a function into another package the function identifier must start with a capital letter.
I recently started learning GO Lang (2 days back)
And what I found was you need to setup a workspace folder to make the local packages import into other projects or main.go files. I'm using VS Code editor. Please correct me if Im wrong, but this setup works fine for me.
Inside your bash_profile OR .zshrc file add below lines, update the GOPATH as per your folder path.
export GOPATH=~/projects/GO_PROJECTS
export PATH=$PATH:$GOPATH/bin:$PATH
and this is my sayHello.go file, please note to be able to export a function the func name should start with a CapitalCase SayHello
package utils
import "fmt"
func SayHello() {
fmt.Println("Hello, Ajinkya")
}
and now I am able to import utils package into main.go file
package main
import (
"go_proj1/utils"
)
func main() {
utils.SayHello()
}
set the current directory as GOPATH
or you can use local import as follows
move your main.go to the ../ directory to the libfastget.go.
i mean the files looks like:
src
|-libfastget
| |-libfastget.go
|
|-main.go
import "./libfastget"

Resources