没有看到结构Golang的公共功能

I don't see the public method of the struct that I defined. Can someone please let me understand why? Here is the code:

// DataSaver.go:

package DataStorage

import (
   "fmt"
   "os"
)

type DataSaver struct {
   // doesn't relevant to my question
   fileName string
   file     *os.File
}

func PrintStr() {
   fmt.Println("hello")
}

Then, I have a main method in other class. I initialized the struct and I wanted to call to PrintStr() function. However, I can't call to this method. Why?

Thank you!

That is not a method, it is just a function.

Import DataStorage (you should make it lower case) then you can call DataStorage.PrintStr()

I had a play around myself with this, and there are a few things to be careful of:

  1. Make sure you import the package properly with respect to your GOPATH, e.g.

    import "github.com/some-repo/datastorage"

And ensure that your packages/repos are in your GOPATH and in the correct directories (go is very fussy about how you do this)

  1. Refer to your function using the package name like so:

    func main(){ DataStorage.PrintStr() }

The other poster is correct in that go conventions are to keep package names in lowercase.

Seems you dont have the concept of method receiver yet. Your method for the struct should be defined as below :

func (this DataSaver)PrintStr() {
   fmt.Println("hello")
}

or

func (this *DataSaver)PrintStr() {
   fmt.Println("hello")
}

which one you choose depends on you want to call the method on a pointer or not;