The Go language implements the Read method for the Fibonacci function

Source: Internet
Author: User

The go language is very flexible, as long as the object implements the appropriate method can be seen as implementing an interface, similar to the Durk Type,

To implement the Read method for Fibonacci, you can read the next Fibonacci value as if you were reading a file.

Example code:

Ackage MainImport (    "FMT"    "io"    "Bufio"    "Strings"    "StrConv") func Fibonacci () Intgen {//Fibonacci sequence, return a intgen type A, B:= 0, 1returnfunc () int {A, B= B, A +breturnA}} Type Intgen func () int//defines a Func type that returns the Int type func (g Intgen) Read (P []byte) (n int, err error) {//implement the Read method for Intgen so that the Printfilecontents function can manipulate next as it reads a file:=g ()ifNext > 100000 {        return0, Io. EOF}S: = Fmt. Sprintf ("%d\n", Next) s:= StrConv. Itoa (Next) +"\ n"    returnStrings. Newreader (s). Read (p)//Use the strings Newreader method to implement the Read interface}func printfilecontents (reader io. Reader) {//read content from reader scanner:=Bufio. Newscanner (reader) forscanner. Scan () {fmt. PRINTLN (scanner. Text ())}}func main () {f:=Fibonacci () printfilecontents (f)}

The Go language implements the Read method for the Fibonacci function

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.