Creating and Using package

Hello Masters,
Probably I am making some nonsense post here and disturbing you, but as a beginner, I want to know how in Go I can implement the following. If I can not, please suggest me suitable solution:
1. Create a package “myNum”
2. containing data type like:
type Num struct {
n, d int // numerator, denominator
3. and a function to print like
func printMyNum(x Num) {
fmt.Println(“the fractional number is: %d/%d”, x.n, x.d)
4. access and use it from “main” both the datatype as well as function
I think for masters, to solve this is a matter of minute. So please help me.
Thank You.

What have you actually tried? What error message do you get?

1 Like

I think you are in the right direction. The name of your variables (including function declarations) must begin with a capital letter in order for you to export it from one package to another. Your struct (Num) will be exported, but your function (printMyNum) will not. You have to call it PrintMyNum.

In your main package you have to import the package:

import “pathfromsrc/myNum”

To use them: myNum.Num and myNum.PrintMyNum.

Was it something like this you were looking for.

1 Like

Hello Sir,
What I was actually trying is:
1. creating a package for fractional number without making it floating point, i.e. keeping numerator and denominator separate in a structure (Num) in the myLib package;
2. creating basic mathematical operations (+,-,*,/) using functions and keeping it in the same package;
3. from main package accessing it and using it;
Now it is working fine.
Now I have posted it to a GitHub repository and trying to use it from there. If you know how to do it, please help to do it.
Thank You.

I do assume, you have your repository at

You then just do import "" wherever you want to use it. You might need to adjust the path, depending on where on github you have placed your files.

Hello Sir,
The previous problem is solved.
And Yes, it is in and I am currently trying what you have told to do.
Thank You Sir.

Thank You Very much. That solved the problem.:grin:

In myGraph (you really shouldn’t use any casing in package names, keep them one word and all lowercase), you should include "" instead of the relative import. Relative imports are not in code that you want to use from other projects, nor are they allowed in projects that want to use dependencies later on.

1 Like

Hello Sir,
1. The casing in the name is to understand and remember the package name. If Go has a problem with it, I will change it, no problem.
2. I am currently working on a project in my computer. But I will change it to URL from relative importing.
I will get back to it soon.
Thank You. :blush:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.