Access to external go files

Hello friends,

I want to ask you about information that confuses me about accessing the function on another page that has been on my mind for a long time.

We can directly import and use functions in external files. Sometimes I see this use of test := &Test{ }, like T t = new T() in c#. Is there any benefit to this, or are there problems with importing and accessing that function directly?

Hi! Direct access is a common practice in programming languages, what you mean for “problems”? Being a statically typed language Go checks all imports, types and functions at compile-time by default and the advantages are clarity and simplicity of writing/reading coding. The module’s name used guarantees the unambiguity of a name. In your case you’re using a pointer to a type that is common and safe in Go (since Go knows that is an heap allocation and works also when you return test from a function). For example this snippet is a possible implementation of your Test type and case:

package main

import (
	"fmt"
	"net/http"
)

type Test http.ServeMux

func main() {
	mux := func() *Test {
		return &Test{}
	}()
	fmt.Printf("%T\n", mux)
}

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