Good Morning All,
I am new to Golang. I want to move some of my functions out into separate files so that I will not have like a 10,000 line .go file at the end. lol. I created two files both have the same package called main. Do I need to change package name to be app specific? Anyway how do I get these two files to talk?
Example:
MainFile.go:
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello World!")
Test()
}
NewFile.go:
package main
import (
"fmt"
)
func Test() {
fmt.Println("Hello World Again!")
}
The test method is in the second file but cannot be reached by the first. I am sure this is some rudimentary thing I am missing.
Thanks
Update:
I tried specifying this on the command line: go build MainFile.go NewSourceFile.go. It comes back with no errors but never builds the binary. How do I get it to output the binary now?
If you run go run MainFile.go, Test() won't be found because its not in that file. You have to build the package then run the package:
Inside the folder where the 2 files are, run go build and you will get a binary in that folder. Then just run the binary: ./MyPackage
Related
PROBLEM: functions exported from other packages are undefined, invisible from inside of main.go
SOLUTION:
Put main.go into a separate folder (name it app or main, doesn't matter). Only go.mod remains in root, with the folders "app" and "package1" "package2" etc. After this VSCode automatically added imports on save, I didn't even need to do anything. If I have main.go in root then it doesn't work (most of the time) as it doesn't "see" functions from other modules (undefined).
I found the solution HERE,(see post by davidbost). The solution on this page by Andrey Dyatlov worked too for a while and then stopped working.
It took me probably 10 hours of try and error and searching.
Hopefully the above will help others. Thank you, everyone!
_______________________________________________________________________
Original Problem Description:
Windows 10, Go 1.17, VS Code with Go extension.
Hello, I am new to Go and I was not able to follow a single tutorial due to the following issue. When I create another .go file in the same directory (or inside a folder of the same directory) as the main.go, I receive error saying .\main.go:7:2: undefined: SayHi
main.go file:
package main
import "fmt"
func main() {
fmt.Println("1st")
SayHi()
}
another .go file inside /something folder:
package something
import "fmt"
func SayHi() {
fmt.Println("Hi!")
}
Running go run main.go results in the undefined SayHi error
I googled the issue with no luck.
$ go build // gives out the same error
$ go install // gives out the same error
without using functions from other files $ go run main.go runs just fine.
I also tried go init with adding my github directory with no luck (by following a tutorial). I also tried the official starting guide with go run init, and the exported Capitalized function is still undefined. What's worse is that autocomplete for the SayHi function works, yet it won't compile because undefined.
I have set PATH to C:\Users\xxx\go and put my files there, I also tried using C:\Go with no luck, it's still undefined. I'm about to give up on Go...
It' would be hard to fix your project without knowing its current state. Please, try to start from scratch:
Create a directory for your project anywhere outside $GOPATH:
mkdir myproject
cd myproject
Run the following command to create a go.mode file that describes your project (module) and its dependencies; let's call the module github.com/me/myproject:
go mod init github.com/me/myproject
Create the first file; let's call it main.go:
package main
import "fmt"
import "github.com/me/myproject/something"
func main() {
fmt.Println("1st")
something.SayHi()
}
Create a directory for the package called github.com/me/myproject/something:
mkdir something
Create a file with path something/something.go:
package something
import "fmt"
func SayHi() {
fmt.Println("Hi!")
}
From the myproject directory, run go build.
Launch your first Go program:
./myproject
1st
Hi!
I've just started learning GO. Ok, I've some weird issue and did not figure out how to fix it.
I have 2 go file. one is main.go and second is state.go and they are both in same package called main.
In state.go file I defined simple function printHello, which then I'm calling it in main.go.
state.go
package main
import "fmt"
func printHello() {
fmt.Println("Hello World!")
}
main.go
package main
func main() {
printHello()
}
When I run it in cmd with command: go run main.go state.go it works fine, but in GoLand IDE it didn't. I tried to build it changed Run Kind to Directory, but without success. Also attached image for more clarification
With main.go opened in the editor.
Click on the green arrow at the left side of main function.
It will run and creates a run configuration that you can customize.
You don't have to run the state.go; just run main.go. The Goland IDE will take care of it since they are in the same package (main).
I'm new to Golang and I'm trying out a few examples as part of my learning. I have 2 Go source files - hello.go and consts.go in my example. consts.go contains some constants which are used by the functions defined in hello.go. When I build both the source files like so:
go build consts.go hello.go and run the output ./hello
the function arrayDemo() is not called at all.
However, when I just run the file hello.go using go run hello.go, the function arrayDemo() is called.
What is the difference in both the approaches that's causing the function not to be called when building?
Here's the code for hello.go:
package main
import (
"fmt"
"os"
"strconv"
"strings"
)
func main() {
fmt.Printf("Speed is %f\n", computeSpeed(54.3, 3.4))
fmt.Printf("%d\n", arrayDemo())
}
func arrayDemo() int32 {
fmt.Println("in arrayDemo")
return 5
}
Code for consts.go:
package main
// Speed speed of a vehicle
type Speed float32
func computeSpeed(dist float32, t float32) Speed {
return Speed(dist / t)
}
go run works because go run works based on file names, but go build works based on package names.
also
go help build says:
When compiling multiple packages or a single non-main package, build
compiles the packages but discards the resulting object, serving only
as a check that the packages can be built.
to my understanding this means you can not have multiple files in the main package and then get working executable by using go build
I have a small go demo project in Gogland with the structure:
awsomeProject
->src
->awsomeProject
->configuration.go
->main.go
Configuration file has a simple structure just for demo:
configuration.go:
package main
type Config struct {
Data int
}
Main file just uses the Config struct:
main.go
package main
import "fmt"
func main(){
var cfg Config
cfg.Data = 1
fmt.Println("lalala")
}
The error that I have is:
/usr/local/go/bin/go run /Users/lapetre/Work/awsomeProject/src/awsomeProject/main.go
command-line-arguments
src/awsomeProject/main.go:6: undefined: Config
Process finished with exit code 2
Any idea why the Config is not seen in main?
Thanks
When you build reusable pieces of code, you will develop a package as a shared library. But when you develop executable programs, you will use the package “main” for making the package as an executable program. The package “main” tells the Go compiler that the package should compile as an executable program instead of a shared library. The main function in the package “main” will be the entry point of our executable program.
That's why you should use the following structure:
awsomeProject
->src
->awsomeProject
->configuration.go
->main.go
with main.go
package main
import "fmt"
func main(){
var cfg awsomeProject.Config
cfg.Data = 1
fmt.Println("lalala")
}
and configuration.go
package awsomeProject
type Config struct {
Data int
}
For more details:
https://golang.org/doc/code.html
https://thenewstack.io/understanding-golang-packages
How are you calling go run? If you're calling it like
go run main.go
then that's the problem.
Go run only runs the file(s) you tell it to. So you need to tell it to also run configuration.go, or if you have several go files to run you can use
go run *.go
as eXMoor suggested.
There are some limits/drawbacks to "go run *.go" however, so the better alternative is to use go build instead of go run.
go build
Will compile everything. Then, to run the executable:
./awesomeProject
To combine all of this into one command that will compile and run whatever app you're working on, you can use:
go build && ./${PWD##*/}
I have it aliased to
gorunapp
just to make it easier.
This may not actually be the answer to the problem you're having, but hopefully you'll find it useful information regardless.
Try to run your application with command:
go run *.go
This question already has answers here:
How can I "go run" a project with multiple files in the main package?
(8 answers)
Closed 6 years ago.
I found this to be a duplicate of this question.
Hello World
Just started learning golang and tried to figure out how to structure a larger program. Not sure if packages are the split I want or if there is something else more suitable for having multiple source files in a single directory, but here's what I tried.
package main
import "fmt"
func main() {
fmt.Printf("hello, world\n")
}
Testing running it:
~/b2/go/src/github.com/bemmu/hello bemmu$ go run hello.go
hello, world
Two file version
I wanted to try splitting it into two files.
main.go
package main
import "fmt"
import "say"
func main() {
say.Hello()
}
say.go
package say
import "fmt"
func Hello() {
fmt.Printf("hello, Go\n")
}
Testing running it:
~/b2/go/src/github.com/bemmu/hello_split bemmu$ go run main.go
main.go:4:8: cannot find package "say" in any of:
/usr/local/go/src/say (from $GOROOT)
/Users/bemmu/b2/go/src/say (from $GOPATH)
In the docs there is an example of creating a library and importing it, but in the example case it is put into a separate directory.
No, Just create a new directory for another package.