Arbitrary data type slicing Golang

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

Package Mainimport ("FMT". "StrConv") type Element interface{}type List []elementtype person struct {name Stringage  int}func (P-person) String () s Tring {return ' my name is ' + P.name + "My age is" + Itoa (p.age)}var slice_1 = []string{"Hello"}var map_1 = Map[string]s tring{' city ': ' Beijing ', ' name ': ' CS ', ' from ': ' USA '}func main () {list: = Make (list, 5) list[0] = 1                    //an intlist[1] = "Hello"              //a stringlist[2] = person{"Barry", +//structlist[3] = slice_1              //a slicelist[4] = map_1                //A MA Pfor _, Element: = Range List {switch v:=element. Type) {//v is a specific value object, and element is the interface object case int:fmt. Println (element, ", int") Case string:fmt. Println (Element, ", string") Case person:fmt. Println (element, ", person struct") default:fmt. Println (Element, ", others like Slice,map ...")}}

The general slice can only hold one data type, but with the interface can be highly abstracted, so that the slice stored data type arbitrary!

Here is an example.



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.