Go language Learning-Methods and interfaces

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

Method:

Refers to a function that contains a recipient, which can be a value of a named type or struct type or a pointer.

Cases:

Type food struct{

Color string

Taste string

}

Func (Fruit Food) Eat () string

{

Return to FMT. Sprintf ("%v,%v)", Fruit.color, Fruit.taset)

}

Food is a structure type, Eat is a method of food type, the recipient of the Eat method is the value of food type (or pointer func (fruit * food) Eat () string).

Apple: = food{"Red", "Sweet"}

Or

Apple: = &food{"Red", "Sweet"}

Method uses

Apple. Eat ()

Interface:

An interface is a type that specifies a set of methods that all methods are considered to be interface types.

A personal understanding interface is defined as a function, and the method is the way to implement this function. Different recipients have different ways to implement this function.

Cases:

Type Judge inerface{

Eat () Food

}

Defines a judge interface and contains a method for Eat ()

Routines

Package Main

Import (
"FMT"
)

Type food struct{
Color string
Taste string
}

Type Judge interface{
Eat () string
}
Func (Fruit *food) Eat () string{
Return to FMT. Sprintf ("%v,%v", Fruit.color,fruit.taste)
}

Type Foodtaste struct{
Taste string
}
Func (Fruit *foodtaste) Eat () string{
Return to FMT. Sprintf ("%v", Fruit.taste)
}

Func Main () {
var a judge
Apple: = food{"Red", "Sweet"}
LEMON: = foodtaste{"Sour"}

A = &apple
Fmt. Println (A.eat ())
A = &lemon
Fmt. Println (A.eat ())
}

Related Article

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.