Golang Parcel Case Pattern

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Learning Golang also has a period of time, but the concept of the package is not very clear, here to simulate a single example of the implementation

    • Deepened the understanding of the package, the use of variable scope in the package
    • Understanding the scope of a package global variable

Directory structure

Mian Method Main.go

package mainimport (    "log"    "p/p1"    _ "t")func main() {    log.Print("-------下面是main-------")    p1.Say()}

Package t T.go

package timport (    "p/p1")func init() {    a := p1.NewPeople()    a.SetName("tttttttt")    a.SetAge(188)    p1.Say()}

Package p/p1 P1.go

package p1import (    "log")var (    single *People)type People struct {    Name string    Age  int}func NewPeople() *People {    if single == nil {        single = new(People)    }    log.Print("new People", single, &single)    return single}func (p *People) SetName(name string) {    p.Name = name}func (p *People) SetAge(age int) {    p.Age = age}func Say() {    log.Print("Say", single, &single)}

Result output

    • The t p1 value after initialization is initialized and output initialized
    • From the results can be seen whether in the package t or mian inside the package, p1 the variable singole is the same address, that is, the implementation of a single case
    • As long as the initialization succeeds, importing in any package p1 can be done directly using the variable Singole

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.