2
votes
package main
import (
......
"fmt"
......
)

func main() {
        ......
    xxx:=new(xxx)
    fmt.Println("1")
        ......
    xxx.Println()//confusing

}
type xxx struct{
    one int
    two string
}
func (yyy *xxx) Println(){
    fmt.Println("2")
    yyy.Print(3)//confusing too
}
func (this *xxx) Print(a int){
    fmt.Println(a)
}

This question is hunted me,what is the fastest way to tell whether it is a package name or an object name,as the code presented above,in the main func,fmt is known as a package name,because everybody knows.But when comes to xxx.Println(),how would you know whether it's a package name or an object name,assuming that the main function contains many lines of code,and it is hard to pin point the declaration of object "xxx",and,there are many packages imported and it is hard for you to search for every line of import() to see if "xxx" is listed in the packages,how do you tell what xxx is?

Same as func Println,you just come straight forward to yyy.Print(3),the receiver in the func declaration is hard to find because it is out of the screen,how would you tell what yyy is the fastest way,yyy could be either the package name and the receiver name.

If there is no such an easier way,does that mean I should always search for the import() listed packages first,and scroll the screen to the very beginning of the func declaration to find what is the receiver name,and then I can know what it is?That sounds to take too much time!

2
It is a valid issue, the package/variable + dotted syntax is confusing, it can be a method invocation or a function call from a package. It makes reading code hard. You have to be aware of the two different interpretations.Bruno Ranschaert

2 Answers

2
votes

For the second question (yyy.Println() inside method Println()), I think it’s standard Go style to name your receivers with very short names. So, standard Go style would suggest:

func (x *xxx) Println() {
    fmt.Println(2)
    x.Print(3)
}

As for the first question… I’m not sure if you’re talking about your code, or somebody else’s code. I would say it’s pretty standard that you eventually learn about what modules a given program or library is using. (Really short variable names, and then camelCase variable names also help.)

1
votes

Using short-term memory, quickly scan the source code for salient features.

package main

import (
    // ......
    "fmt"
    // ......
)

type xxx struct {
    one int
    two string
}

func (this *xxx) Print(a int) {
    fmt.Println(a)
}

func (yyy *xxx) Println() {
    fmt.Println("2")
    yyy.Print(3) // yyy is receiver *xxx
}

func main() {
    // ......
    xxx := new(xxx)
    fmt.Println("1")
    // ......
    xxx.Println() // xxx is var xxx
}

Apply the language rules. For example, block and scope rules.

With practice, it's easy.

References:

The Go Programming Language Specification

Import declarations

Qualified identifiers

Selectors

Blocks

Declarations and scope