Daily Go Language Bible-Interface Conventions Exercise 2

Source: Internet
Author: User

Exercise 7.3: Implement a String method for the *tree type in Gopl.io/ch4/treesort (§4.4) to show a sequence of values for the tree type.

Package Mainimport ("FMT" "bytes") Func main () {//definition array arr:=[...] int{6,2,1,3,4,5} var t *tree for I:=0;i<len (arr); i++{T=add (T,arr[i])}/ /t1:=sort (arr[:],t)//fmt. Println (arr) fmt. Println (t)}/* Exercise 7.3: Implement a String method for the *tree type in Gopl.io/ch4/treesort (§4.4) to display a sequence of values for the tree type. */func (t *tree) String () string{var buf bytes. Buffer var data []int data=appendvalues (data,t) buf. WriteByte (' {') for _,v:=range data{if buf. Len () > Len ("{") {buf. WriteByte (")}//Focus: Using the interface Convention FMT. fprintf (&buf, "%d", V)} buf. WriteByte ('} ') return BUF. String ()}type tree struct {value int left, right *tree}//sort sorts values in place.func sort (values []int, Root *tree) *tree {//var root *tree for _, V: = range values {root = Add (root, V)} FMT. Println (Root) appendvalues (values[:0], root) return root}//Appendvalues appends the elements of T to values in order//and R Eturns the resulting slice.func appendvalues (values []int, T *tree) []int {if t! = Nil {values = Appendvalues ( values, t.left) values = Append (values, t.value) values = Appendvalues (values, t.right)} return value        S}func Add (t *tree, value int) *tree {if T = = nil {//equivalent to return &tree{value:value}.    t = new (tree) T.value = value return T} if value < T.value {T.left = Add (t.left, value) } else {t.right = Add (t.right, value)} return T}

  

Daily Go Language Bible-Interface Conventions Exercise 2

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.