How do you implement a container for different types in Go? [duplicate]

<div class="question-status question-originals-of-duplicate">

This question already has an answer here:

    <li> What would generics in Go be? <span class="question-originals-answer-count"> 2 answers </span> </li> </ul>

    The following code implements a List of ints in Go:

    package main import "fmt" type List struct { Head int Tail *List } func tail(list List) *List { return list.Tail } func main() { list := List{Head: 1, Tail: &List{Head: 2, Tail: &List{Head: 3, Tail: nil}}} fmt.Println(tail(list).Head) }

    Problem is this only works for int. If I wanted a list of strings, <strong>I'd need to re-implement every list method (such as tail) again!</strong> That's obviously not practical, so, this can be solved by using an empty interface:

    type List struct { Head interface{} // Now works for any type! Tail *List }

    Problem is, 1. this seems to be much slower because of type casts, 2. it throws aways type safety, allowing one to type-check anything:

    // This type-checks! func main() { list := List{Head: 123456789 , Tail: &List{Head: "covfefe" , Tail: &List{Head: nil , Tail: &List{Head: []int{1,2}, Tail: nil}}}} fmt.Println(tail(list).Head)

    Obviously that program should not type-check in a statically typed language.

    How can I implement a List type which doesn't require me to re-implement all List methods for each contained type, but which keeps the expected type safety and performance?


    Go doesn't have generic types, so you're stuck with the options you listed. Sorry.

    Meanwhile, Go's built-in maps and slices, plus the ability to use the empty interface to construct containers (with explicit unboxing) mean in many cases it is possible to write code that does what generics would enable, if less smoothly.

    If you know more about the elements you want to store in the container, you may use a more specialized interface type (instead of the empty interface interface{}), which

      <li>could help you avoid using type assertions (<strong>keep good performance</strong>)</li> <li>and still <strong>keep type safety</strong></li> <li>and it can be used for all types that (implicitly) implement your interface (<strong>code "re-usability"</strong>, no need to duplicate for multiple types).</li> </ul>

      But that's about it. See an example of this here: Why are interfaces needed in Golang?

      Also just in case you missed it, the standard library already has a doubly linked list implementation in the container/list package (which also uses interface{} type for the values).


      It's important to acknowledge that we expect generic types to be slower, not faster. The excellent fastutil library for Java outperforms the more flexible classes from the standard library by using concrete implementations.

      Russ Cox (one of Go's authors) summarises the situation like this:

        <li>(The C approach.) Leave them out.
          <li>This slows programmers. </li> </ul></li> <li>(The C++ approach.) Compile-time specialization or macro expansion.
            <li>This slows compilation. </li> </ul></li> <li>(The Java approach.) Box everything implicitly.
              <li>This slows execution.</li> </ul></li> </ul>

              You may be interested in this living document which has a lot of the pros and cons outlined.

              As the other answer points out, Go does not support the design you're trying to achieve here. Personally, I'd just duplicate the code - it's not much, the tests are cheap, and most of the time you don't actually need the generic behaviour you want to implement.


              As icza mentioned there isn't a straightforward way.

              You could try using code generation to generate methods for new types.


  • Custom Binary Input - Hadoop
  • SQL Server 2008 Using RANK to Dynamically Number Rows
  • ASP.NET Web API XmlFormatter does not work, falls back to JsonFormatter
  • FMDatabase.h not found when using route-me library
  • app-script google doc copy table with inline image
  • C++ - Reading a double, followed by a character, from cin
  • Underscore JS difference on array and array with objects
  • CoreData predicate for one to many relationship
  • Need to loop through an array that is inside of another array
  • Python flatten list (but not all the way)
  • Getting value from iframe to iframe
  • WPF: TextTrimming in CheckBox with no fixed width
  • Selective Color of image
  • horizontal uiview's controls unresponsive.. or how to foul up a view hierarchy
  • MATLAB parse and store XML with XSD
  • Building the tables for an Auto-drop subscription system
  • iPhone - Changing a sub-sub-sub NSMutableDictionary value
  • XDocument.Parse: Avoid replacing XXE references
  • A program sharing TEXT with its copy (opened twice)
  • How to combine multiple dicts, summing the values of common keys (and retaining those with value 0)
  • Understanding generics and Func arguments
  • MailCore: Offline HTML Rendering
  • Find a value which contains in ALL rows of a table
  • Websphere: Does parent_last affect other applications?
  • Sailsjs view caching (bug ?)
  • How can I install php on Windows
  • Correct way to clear floating elements inside
  • Persistence in a JavaScript module
  • Visual C++'s implementation of std::map
  • Dynamic Injection in Angular, injecting a component to parent component
  • Excel vba list box multi column multi row from 14 text boxes
  • Properties shared between child and parents class in php
  • Automatically clear contents securely of C++ std::string and std::vector on destructor [duplicate]
  • Efficiently find matching rows (based on content) in a pandas DataFrame
  • NEON assembly fail to build for iOS in XCode 4.3.2
  • Animating Tiles In My Game
  • JavaFX WebView doesn't execute JavaScript
  • How to assign enum to variable
  • Receive Android NotificationManager Notifications from Non-System Apps
  • Passing params from within to action specified in createLink within a javascript function, called o
  • Batch file to Sort folders
  • Batch file to Move files based on part of filename, to folder based on part of folder name
  • Read binary matrix from a file in Matlab
  • More than one conditions in Where clause of Fusion Table Layer ignored in Styles
  • Why are unboxed arrays not an instance of foldable?
  • changing a string value throws segmentation fault [duplicate]
  • How to create a new r dataframe variable contingent on existing variables
  • What is the correct way to convert my IP Packet data into a String?
  • Using SSMTP and ProcessBuilder
  • Android: how to show images in ImageSwitcher
  • How to setup different environments and corresponding configurations under sails.js?
  • How to disable hyperlinks within a PDF rendered by PDF.js
  • CSS width 100% no working
  • Graphics2D does PostModern
  • MySQL Full Text Search Not Matching
  • Primary FFT Coefficients vs Low-Pass Filter
  • Scan html files in poedit
  • how to use .getelementbyID and copy inner html - VBA
  • Collect array of successful promises
  • Has anyone successfully exported xidel output vars to cmd?
  • Regex to remove html tags with certain class from string [duplicate]
  • Read from File Variance Calculation
  • .NET Regex expression to parse list of numbers and number ranges
  • django - render_to_string not working
  • Resized NSImageView not redrawing
  • While extracting text from PDF file using iTextSharp, I am getting this error: “Could not find image
  • How can I avoid this inline Javascript?
  • Markdown Report Not Executing in Rstudio
  • java.lang.NoClassDefFoundError: org/apache/tools/ant/util/ReaderInputStream vaadin+gradle+intelliJ
  • Updating once deployed
  • While statment with multiple values contained in an array
  • Order By clause on an aggregated SQL request
  • Unmapping Vim Plugin mappings
  • How to Validate binded WPF TextBoxes which is depend on each other's value and how to enable/di
  • Prism v4: Unity or MEF?
  • Point Cloud Library (PCL) basic tutorial cmake and make errors on Ubuntu 16.04
  • get current page/url in attribute selector
  • string.replace(fromCharCode() , '') cannot replace characters
  • How can I return mysql search results where only the columns with non-null entries are displayed
  • Replace JTextField with an Image?
  • stumped on a Java interview, need some hints
  • Concatenation of two Java strings [duplicate]
  • Mapping a class that consists only of a composite PK without @IdClass or @EmbeddedId
  • Unable to convert .jks to .pkcs12: excess private key
  • Checking for date overlap across multiple date range objects
  • How to Sum multiple Column with multiple value
  • Parsing Text Files
  • How to take means of each row in R if data is of character or factor type? [duplicate]
  • Is it possible to use the same package and class name in Eclipse plugins with different ID?
  • What is the best way to distribute as3 classes and packages? [closed]
  • Missing definition of 'algebraic data type' in the book “Learn You a Haskell for Great Goo
  • Is this a valid use of a conditional expression?
  • Select first and last match by column from a timestamp-ordered table in MySQL
  • C#: How to prevent a textbox' content from being scrolled up on Enter?
  • xPath doesn't retrieve HTML as part of what is needed [duplicate]
  • Limit characters per line in the multiline textbox in windows form application
  • How do I assign blank space in a div and the button within with the same functionality?
  • Java File I/O - Text File - How to check for content?
  • Muenchian Grouping with XSL-FO Table
  • box-shadow being cut off
  • Trouble with my enhanced for loop? [closed]
  • How do you make the radio button text to be clickable too?
  • deleting a void pointer using delete operator [duplicate]
  • Correct way to use a default date in a django model
  • How to show contents with punctuation in columns
  • Can I place inside [closed]
  • The difference between a/ and a/* and a/** in .gitignore?
  • is this a case of association or aggregation?
  • Determine how many characters in text are within another text entry in MySQL
  • How to append columns based on other column values to pandas dataframe
  • Does polluting the $scope object affect performance?
  • LINQ to SQL many to many int ID array criteria query
  • Is that possible to find width and height of an image using PHP DOM?
  • Hibernate Documentation: Parent/Child type relationship
  • How do I see the message for a http-response-code 406 exception
  • How to get a list of dbids contained in a layer?
  • 'Characters only' check in xsl string?
  • Copying files to new directory in SBT
  • Model layer dependency on MVC attributes
  • Select a all tables within table using Word Macro
  • Save Image to word of HTML reference
  • How to pass special characters in a URL
  • Can't start Gtk# Mono App without IDE (Unable to load DLL “intl”)
  • C# modifying string array from one scope level down
  • setting the selected option of a select tag with jquery
  • causes of Python IOError: [Errno 13] Permission denied
  • With Web projects Asp.Net only detects changes in aspx, but not cs files
  • How to scrape contents from dynamic webpage in PHP? [closed]
  • Glassfish: how to investigate roles/groups problems
  • Initialize React Google Maps StandaloneSearchBox with geocode
  • From the perspective of an ASP.Net web form, can the Request.UserHostAddress be trusted?
  • Wireshark tcap dissector inside my program
  • What is the name of this URL part?
  • What is the idiomatic way to copy a ZipEntry into a new ZipFile?
  • How to create a shared folder between Homestead and my local machine
  • What to put in Business Logic Layer? [closed]
  • Dealing with many […] in Ruby
  • jquery remove part of string between [[ and ]]
  • What is the git clone --filter option's syntax?
  • what is use of Tuple.getStringByField(“ABC”) in Storm
  • Jquery adding click function to several spans with the same Class
  • Is there an expiring map in Java that expires elements after a period of time since *first* insertio
  • Getting the last backslash in a filepath via regex
  • Column invalid in the select list because it is not contained in either an aggregate function or the
  • How list comprehensions are evaluated in python and in what order
  • Maven, javadoc : No source files for package
  • Is there a good treeview control supports ajax searching,filtering?
  • How to add text to last row of a column
  • Comparing lists of different types
  • Check if two list have the same items
  • Inconsistent Results from javax.print library
  • MVVM Validation in UWP
  • Select Subset of Columns based on Vector R
  • Spring JPA repository Converter not found
  • scale div to background image size
  • Getting Group Claims With ADFS 4.0 OAuth2 Token
  • Unable to scrape the text from a certain LI element
  • sql group by and max and other values
  • Addressing issue with mov instruction in x86
  • shrinking flexboxes to the same height of the shortest box [duplicate]
  • Filter strings in a for loop by list of words for reddit bot
  • How do I style my XPages InputTextarea so it shows full height dependent on content? (in both edit a
  • Adding elements to List
  • How to guide GCC optimizations based on assertions without runtime cost?
  • Find which assembly instruction caused an Illegal Instruction error without debugging
  • How to build and use epgsql (erlang)
  • Javax Websocket closing due to Illegal UTF-8 Sequence
  • SQL Query Error in Group By and Order By Clause
  • Convert swf file to mp4 using ffmpeg
  • Apache POI : Difference between row.getLastCellNum and row.getNoOfPhysicalCell
  • UIScrollView won't scroll!
  • Java prints array memory address rather than array contents [duplicate]
  • RequiredFieldValidator and preventing CausesValidation
  • Blackberry Error: Cannot run program “jar”: CreateProcess error=2, The system cannot find the file s
  • Ansible/Jinja: condition with an undefined statement
  • Matlab reading from serial port at specific sampling rate
  • Javascript and bookmarks
  • Why does mariadb regex give contrary result?
  • How to make s3 bucket public in python
  • Check if tables are identical using SQL in Oracle
  • Module or main program array must have constant shape error in Fortran
  • Is there a limit on PHP Variable Size?
  • Regular expression to escape regular expressions
  • ASP.Net Webservice Serialization
  • Ansible/Jinja: condition with an undefined statement
  • Vim syntax files: add to cterm
  • How to run Abaqus Macro (.py) script
  • How to Exclude directory and its contents in gradle war
  • In Linq-to-Nhibernate, is it possible to use .Fetch() after a .Select()?
  • Find/sed: How can I recursively search/replace a string in files but only for lines that match a par
  • Accessing unallocated memory C++
  • How do I manipulate html returned in an ajax response?
  • MongoDB Calculate Values from Two Arrays, Sort and Limit
  • How do I loop through cells and create a new row if it contains a specific string in vba?
  • PHP email validation script
  • Julia+JuMP: variable number of arguments to function
  • Php Destruct Called Twice
  • how to model a parse class to include isliked, isfollowing fields along with the PFQuery results
  • Looping through a map data structure in Haskell
  • how to add. JAR in my project? [duplicate]
  • What is the Programdata/Application Data folder?
  • Javascript Function Expressions
  • Getting data out of a Silverlight control
  • Create a top down parser based on a custom language
  • what's the alternative of set object = null in C++ like C#
  • Compare and jump instruction as one instruction
  • Facebook HTML5 Like Button - Hide Comment Popup
  • Alternatives to server controls in MVC
  • Different Styles for same class name but different id
  • Load frequent subsequences from TXT
  • How to rebuild newlib and newlib-nano of GNU Arm Embedded Toolchain
  • Server Side Includes vs. ASP.NET Techniques is there a performance difference?
  • Eclipse not using jars from add classpath variable
  • Jquery - Copy div contents to clipboard
  • Unit Testing the IoC container itself
  • SQLCipher iOS OpenSSL Build error: line 66: ./config: No such file or directory
  • Updating UITableView that is managed by NSFetchedResultsController and has 1 extra cell in the first
  • How to extract the color of a rectangle in a PDF, with iText
  • Matlab: Find area enclosed by points (x,y)
  • Add-Type in a function contained in a module
  • Bind ajax request to specific element Rails 3.1
  • Find XmlNode where attribute value is contained in string
  • Predict/estimate values using randomForest in R
  • PowerShell understand Get-Member
  • Hudson: What is a good way to store a variable between the two job runs?
  • rvest package - Is it possible for html_text() to store an NA value if it does not find an attribute
  • Delayed “rendering” of WPF/Silverlight Dependency Properties?
  • Should I define my Cython function using def, cdef, or cpdef for optimal performance?
  • What is 1NF truly?
  • Apache POI 3.17 in OSGi
  • When functionalities of html attributes and css styles overlap
  • Get Original Source code of the URL in Webbrowser Control
  • Static const int not good enough for array size?
  • Extracting data from a string where the data structure is embedded in the string itself
  • “Where” statement: match a single word (not substring)
  • Custom perl installation cannot find Git.pm
  • dreferencing 2 d array
  • Android: playing audio files in /res/raw by file name
  • Write a function that calculate the sum of integers in a list in Erlang
  • Writing Unittest for generic classes… best approach?
  • ViewData, ViewBag and TempData violates MVC? [closed]
  • FluentMigrator Failed Migrations Don't Rollback?
  • Microsoft Chart Controls for Microsoft .NET Framework 4.0
  • How to get ATL support into an existing Windows application
  • Extracting individual digits from a float
  • Mongodb update() vs. findAndModify() performace
  • It is possible use the same sql azure instance from two different cloud service of two different sub
  • How to open multiple instances of a program in Linux
  • Efficient algorithm to find additions and removals from 2 collections
  • include dlls in visual studio c++ 2008
  • Why must we declare a variable name when adding a method to a struct in Golang?
  • KnockoutObservableArray with typed elements in TypeScript
  • How to pass a value from ASP.NET MVC controller to ASP.NET webforms control inside MVC View?
  • how do i write assembly code from c#?
  • NUnit 3.0 TestCase const custom object arguments
  • Memory error in python- how to use more memory
  • Differences in dis-assembled C code of GCC and Borland?
  • rspec simple example getting error on request variable in integration test
  • MySQL Order by column = x, column asc?
  • What does 'Language neutral' mean with regard to MAKELANGID?
  • Android activity accessing service's static reference before the service is ready
  • PHP buffered output depending on server setting?
  • How to attach a node.js readable stream to a Sendgrid email?
  • Functions in global context
  • Row Count Is Returning the incorrect number using RaptureXML
  • Switching to Release Build causes runtime error in Web Reference
  • Exception “firebase.functions() takes … no argument …” when specifying a region for a Cloud Function
  • Algorithm for a smudge tool?
  • Is my CUDA kernel really runs on device or is being mistekenly executed by host in emulation?
  • Azure Cloud Service Web Role web pages do not load
  • Spray.io: When (not) to use non-blocking route handling?
  • swift auto completion not working in Xcode6-Beta
  • Is possible to count alias result on mysql
  • Finding past revisions of files in StarTeam w/ .NET SDK / C#
  • Check if a string to interpolate provides expected placeholders
  • Cannot Parse HTML Data Using Android / JSOUP
  • C# - Getting references of reference
  • Checking variable from a different class in C#