Golang interface Assignment

Source: Internet
Author: User



12345678910111213141516171819202122232425262728293031 package main  import ( "fmt" )  type LesssAdder interface {   Less(b Integer) bool   Add(b Integer) }  type Integer int  func (a Integer) Less(b Integer) bool {   return a < b }  func (a *Integer) Add(b Integer) {   *a += b }  func main() {    var a Integer = 1   var b LesssAdder = &a   fmt.Println(b)    //var c LesssAdder = a   //Error:Integer does not implement LesssAdder    //(Add method has pointer receiver) }

The go language can be based on the following functions:

?

1 func (a Integer) Less(b Integer) bool

Automatically generate a new less () method

?

1 func (a *Integer) Less(b Integer) bool

Thus, the type *integer has both Less() a method and a Add() method to satisfy the Lessadder interface. And according to

?

1 func (a *Integer) Add(b Integer)

This function cannot generate the following member methods:

?

123 func(a Integer) Add(b Integer) {   (&a).Add(b) }

Because (&a).Add() only the function parameter A is changed, there is no effect on the object that is actually being manipulated externally (value passing), which does not conform to the user's expectations. So the go language does not automatically generate this function for it. Therefore, the type integer only has the less () method, the missing Add() method, and the Lessaddr interface is not satisfied. (It can be understood that object functions of pointer types are readable and writable, non-pointer-type Object functions are read-only) assign one interface to another interface in the go language, as long as two interfaces have the same list of methods (the order does not matter), then they are equivalent and can be assigned to each other. If the method list of the A interface is a subset of the method list of interface B, then interface B can be assigned to interface A, but the reverse is not possible and cannot be compiled.


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.