Golang importing custom structures, implementing interfaces

Source: Internet
Author: User

Project root directory is Mygo, new go file, write an entry function

package mainfunc main() {    }

Create a new model folder and create a new. Go file (with no arbitrary file name), customize the structure

package peopletype Info struct {    Age int}type People struct {    Name string    Info Info}func (p People) Getname() string {    return p.Name}func (p People) Setname(name string) People {    p.Name = name    return p}

声明首字母大写可供外部调用

Create a new Imp folder to put the interface file, create a new. Go file, write an interface

package peopleiimport "mygo/model" //导入刚才的定义的结构体包type PeopleI interface {    Getname() string  // 返回类型string    Setname(name string) people.People  //放回类型为people}

Importing custom structures into the portal file and implementing interfaces

package mainimport (    "fmt"    "mygo/model" //结构体    "mygo/imp" //接口目录)func main() {    var pi peoplei.PeopleI = new(people.People); //声明接口    p := pi.Setname("dagx") //Setname返回结构体,此处声明p并赋值    p.Info.Age = 10;    fmt.Print(p.Getname(), ":", p.Info.Age)}

Summarize

    • 1. Import Package Imports is a folder, not a file name, the name of the files and import and call Independent

    • 2. The name of the package is called, regardless of the file name

    • 3. The property method is capitalized first, otherwise it cannot be called

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.