The Go programming language

The Go Programming Language

Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.

Gopher image Gopher image by Renee French, licensed under Creative Commons 3.0 Attributions license.

Our canonical Git repository is located at https://go.googlesource.com/go. There is a mirror of the repository at https://github.com/golang/go.

Unless otherwise noted, the Go source files are distributed under the BSD-style license found in the LICENSE file.

Download and Install

Binary Distributions

Official binary distributions are available at https://golang.org/dl/.

After downloading a binary release, visit https://golang.org/doc/install or load doc/install.html in your web browser for installation instructions.

Install From Source

If a binary distribution is not available for your combination of operating system and architecture, visit https://golang.org/doc/install/source or load doc/install-source.html in your web browser for source installation instructions.

Contributing

Go is the work of thousands of contributors. We appreciate your help!

To contribute, please read the contribution guidelines: https://golang.org/doc/contribute.html

Note that the Go project uses the issue tracker for bug reports and proposals only. See https://golang.org/wiki/Questions for a list of places to ask questions about the Go language.

Owner
Go
The Go Programming Language
Go
Comments
  • I have already used the name for *MY* programming language

    I have already used the name for *MY* programming language

    by fmccabe:

    I have been working on a programming language, also called Go, for the last 10 years.
    There have 
    been papers published on this and I have a book.
    
    I would appreciate it if google changed the name of this language; as I do not want to
    have to 
    change my language!
  • proposal: spec: generic programming facilities

    proposal: spec: generic programming facilities

    This issue proposes that Go should support some form of generic programming. It has the Go2 label, since for Go1.x the language is more or less done.

    Accompanying this issue is a general generics proposal by @ianlancetaylor that includes four specific flawed proposals of generic programming mechanisms for Go.

    The intent is not to add generics to Go at this time, but rather to show people what a complete proposal would look like. We hope this will be of help to anyone proposing similar language changes in the future.

  • Proposal: A built-in Go error check function,

    Proposal: A built-in Go error check function, "try"

    Proposal: A built-in Go error check function, try

    This proposal has been closed. Thanks, everybody, for your input.

    Before commenting, please read the detailed design doc and see the discussion summary as of June 6, the summary as of June 10, and most importantly the advice on staying focussed. Your question or suggestion may have already been answered or made. Thanks.

    We propose a new built-in function called try, designed specifically to eliminate the boilerplate if statements typically associated with error handling in Go. No other language changes are suggested. We advocate using the existing defer statement and standard library functions to help with augmenting or wrapping of errors. This minimal approach addresses most common scenarios while adding very little complexity to the language. The try built-in is easy to explain, straightforward to implement, orthogonal to other language constructs, and fully backward-compatible. It also leaves open a path to extending the mechanism, should we wish to do so in the future.

    [The text below has been edited to reflect the design doc more accurately.]

    The try built-in function takes a single expression as argument. The expression must evaluate to n+1 values (where n may be zero) where the last value must be of type error. It returns the first n values (if any) if the (final) error argument is nil, otherwise it returns from the enclosing function with that error. For instance, code such as

    f, err := os.Open(filename)
    if err != nil {
    	return …, err  // zero values for other results, if any
    }
    

    can be simplified to

    f := try(os.Open(filename))
    

    try can only be used in a function which itself returns an error result, and that result must be the last result parameter of the enclosing function.

    This proposal reduces the original draft design presented at last year's GopherCon to its essence. If error augmentation or wrapping is desired there are two approaches: Stick with the tried-and-true if statement, or, alternatively, “declare” an error handler with a defer statement:

    defer func() {
    	if err != nil {	// no error may have occurred - check for it
    		err = …	// wrap/augment error
    	}
    }()
    

    Here, err is the name of the error result of the enclosing function. In practice, suitable helper functions will reduce the declaration of an error handler to a one-liner. For instance

    defer fmt.HandleErrorf(&err, "copy %s %s", src, dst)
    

    (where fmt.HandleErrorf decorates *err) reads well and can be implemented without the need for new language features.

    The main drawback of this approach is that the error result parameter needs to be named, possibly leading to less pretty APIs. Ultimately this is a matter of style, and we believe we will adapt to expecting the new style, much as we adapted to not having semicolons.

    In summary, try may seem unusual at first, but it is simply syntactic sugar tailor-made for one specific task, error handling with less boilerplate, and to handle that task well enough. As such it fits nicely into the philosophy of Go. try is not designed to address all error handling situations; it is designed to handle the most common case well, to keep the design simple and clear.

    Credits

    This proposal is strongly influenced by the feedback we have received so far. Specifically, it borrows ideas from:

    Detailed design doc

    https://github.com/golang/proposal/blob/master/design/32437-try-builtin.md

    tryhard tool for exploring impact of try

    https://github.com/griesemer/tryhard

  • proposal: Go 2: simplify error handling with || err suffix

    proposal: Go 2: simplify error handling with || err suffix

    There have been many proposals for how to simplify error handling in Go, all based on the general complaint that too much Go code contains the lines

    if err != nil {
        return err
    }
    

    I'm not sure that there is a problem here to be solved, but since it keeps coming up, I'm going to put out this idea.

    One of the core problems with most suggestions for simplifying error handling is that they only simplify two ways of handling errors, but there are actually three:

    1. ignore the error
    2. return the error unmodified
    3. return the error with additional contextual information

    It is already easy (perhaps too easy) to ignore the error (see #20803). Many existing proposals for error handling make it easier to return the error unmodified (e.g., #16225, #18721, #21146, #21155). Few make it easier to return the error with additional information.

    This proposal is loosely based on the Perl and Bourne shell languages, fertile sources of language ideas. We introduce a new kind of statement, similar to an expression statement: a call expression followed by ||. The grammar is:

    PrimaryExpr Arguments "||" Expression
    

    Similarly we introduce a new kind of assignment statement:

    ExpressionList assign_op PrimaryExpr Arguments "||" Expression
    

    Although the grammar accepts any type after the || in the non-assignment case, the only permitted type is the predeclared type error. The expression following || must have a type assignable to error. It may not be a boolean type, not even a named boolean type assignable to error. (This latter restriction is required to make this proposal backward compatible with the existing language.)

    These new kinds of statement is only permitted in the body of a function that has at least one result parameter, and the type of the last result parameter must be the predeclared type error. The function being called must similarly have at least one result parameter, and the type of the last result parameter must be the predeclared type error.

    When executing these statements, the call expression is evaluated as usual. If it is an assignment statement, the call results are assigned to the left-hand side operands as usual. Then the last call result, which as described above must be of type error, is compared to nil. If the last call result is not nil, a return statement is implicitly executed. If the calling function has multiple results, the zero value is returned for all result but the last one. The expression following the || is returned as the last result. As described above, the last result of the calling function must have type error, and the expression must be assignable to type error.

    In the non-assignment case, the expression is evaluated in a scope in which a new variable err is introduced and set to the value of the last result of the function call. This permits the expression to easily refer to the error returned by the call. In the assignment case, the expression is evaluated in the scope of the results of the call, and thus can refer to the error directly.

    That is the complete proposal.

    For example, the os.Chdir function is currently

    func Chdir(dir string) error {
    	if e := syscall.Chdir(dir); e != nil {
    		return &PathError{"chdir", dir, e}
    	}
    	return nil
    }
    

    Under this proposal, it could be written as

    func Chdir(dir string) error {
    	syscall.Chdir(dir) || &PathError{"chdir", dir, err}
    	return nil
    }
    

    I'm writing this proposal mainly to encourage people who want to simplify Go error handling to think about ways to make it easy to wrap context around errors, not just to return the error unmodified.

  • spec: add generic programming using type parameters

    spec: add generic programming using type parameters

    We propose adding support for type parameters to Go. This will change the Go language to support a form of generic programming.

    A detailed proposal document has been published, with input from many members of the Go community. We are now taking the next step and proposing that this document become a part of the language.

    A very high level overview of the proposed changes:

    • Functions can have an additional type parameter list that uses square brackets but otherwise looks like an ordinary parameter list: func F[T any](p T) { ... }.
    • These type parameters can be used by the regular parameters and in the function body.
    • Types can also have a type parameter list: type MySlice[T any] []T.
    • Each type parameter has a type constraint, just as each ordinary parameter has a type: func F[T Constraint](p T) { ... }.
    • Type constraints are interface types.
    • The new predeclared name any is a type constraint that permits any type.
    • Interface types used as type constraints can have a list of predeclared types; only type arguments that match one of those types satisfy the constraint.
    • Generic functions may only use operations permitted by their type constraints.
    • Using a generic function or type requires passing type arguments.
    • Type inference permits omitting the type arguments of a function call in common cases.

    For more background on this proposal, see the recent blog post.

    In the discussion on this issue, we invite substantive criticisms and comments, but please try to avoid repeating earlier comments, and please try to avoid simple plus-one and minus-one comments. Instead, add thumbs-up/thumbs-down emoji reactions to comments with which you agree or disagree, or to the proposal as a whole.

    If you don't understand parts of the design please consider asking questions in a forum, rather than on this issue, to keep the discussion here more focused. See https://golang.org/wiki/Questions.

  • proposal: Go 2 error values

    proposal: Go 2 error values

    This issue is for discussion of our Go 2 error values proposal, which is based on our draft designs for error information and formatting.

    This proposal will follow the process outlined in the "Go 2, here we come" blog post: we will have everything ready to go and checked in at the start of the Go 1.13 cycle (Feb 1), we will spend the next three months using those features and soliciting feedback based on actual usage, and then at the start of the release freeze (May 1), we will make the "launch decision" about whether to include the work in Go 1.13 or not.

    Update 2019-05-06: See launch decision here: https://github.com/golang/go/issues/29934#issuecomment-489682919

  • Proposal: Alias declarations for Go

    Proposal: Alias declarations for Go

    Abstract We propose to add alias declarations to the Go language. An alias declaration introduces an alternative name for an object (type, function, etc.) declared elsewhere. Aliases simplify splitting packages because clients can be updated incrementally, which is crucial for large-scale refactoring.

    Motivation During refactoring, it is often desirable to split an existing package into multiple packages. Exported objects such as types, functions, etc. that move from one package to another will require clients to be updated accordingly. In a continuous build environment, build breakages are the consequence if not all clients can be updated simultaneously.

    This is a real issue in large-scale systems such as we find at Google and other companies because the number of dependencies can grow into the hundreds if not thousands. Client packages may be under control of different teams and evolve at different speeds. Updating a large number of client packages simultaneously may be close to impossible. This is an effective barrier to system evolution and maintenance.

    Go trivially permits constants to refer to other constants, possibly from another package. Similarly, if a function moves from one package to another, a “forwarder” function that simply calls the moved function may be left behind so clients can continue to refer to the old package. These techniques enable incremental update of clients without breaking a continuous build system.

    No such work-around exists for types and variables. To address the issue, we propose the notion of a general alias declaration. An alias declaration introduces an alternative name for an object (constant, type, variable, or function) declared elsewhere, possibly in another package. An alias may be exported, so clients can refer to on object via the package that declares the object, or any package exporting an alias to an object, and get the same object.

    Alias declarations are designed such that they fit seamlessly in the existing language spec without invalidating backward-compatibility or any other aspect of the Go 1 guarantees. Tools that process Go code which will require changes to support alias declarations.

    Alias declarations are a compile-time mechanism and don’t incur any runtime costs.

    The design document (forthcoming) describes alias declarations in detail.

    Added July 25, 2016: Link to design document: https://github.com/golang/proposal/blob/master/design/16339-alias-decls.md

  • spec: generics: use type sets to remove type keyword in constraints

    spec: generics: use type sets to remove type keyword in constraints

    We propose clarifications for the semantics of constraint satisfaction in the generics proposal. We also propose changing the syntax of type lists to remove the type keyword and to explicitly specify when type arguments should match on underlying types.

    The changes this would make to the current generics proposal document can be seen in https://golang.org/cl/306689.

    Background

    The current generics proposal proposes a new syntax for type lists within interfaces. A type list within an interface is the keyword type followed by a list of types separated by commas. Type lists are only permitted in interface types that are used as type constraints. For example:

    // SignedInteger is a type constraint that permits any
    // signed integer type.
    type SignedInteger interface {
    	type int, int8, int16, int32, int64
    }
    

    A type argument matches a constraint with a type list if

    1. The type argument implements the interface ignoring the type list, and
    2. either the type argument or its underlying type is identical to one of the types in the type list.

    This rule was adopted in part to support permitting type lists in ordinary interface types, not only in constraints. However, discussion has made clear that the rule is too subtle. This suggests that it is too subtle not just for use in ordinary interface types, but also for use in constraints.

    The behavior when embedding interfaces with type lists is also subtle.

    We can do better.

    Type sets

    We start by defining a type set for all types. We will define what it means for a type to implement an interface in terms of type sets, resulting in a behavior that is equivalent to the current definition based on method sets.

    Every type has an associated type set. The type set of an ordinary non-interface type T is simply the set {T} which contains just T itself. The type set of an interface type (in this section we only discuss ordinary interface types, without type lists) is the set of all types that declare all the methods of the interface.

    Note that the type set of an interface type is an infinite set. For any given type T and interface type IT it's easy to tell whether T is in the type set of IT (by checking whether all methods of IT are declared by T), but there is no reasonable way to enumerate all the types in the type set of IT. The type IT is a member of its own type set because an interface inherently declares all of its own methods. The type set of the empty interface interface{} is the set of all possible types.

    With this idea of type sets, we can restate what it means for a type T to implement an interface type IT: T implements IT if T is a member of the type set of IT. Since the type set of IT is the set of all types that declare all the methods of the interface, T is a member of the type set of IT if and only if the method set of T is a (possibly improper) superset of the method set of IT, which is the standard definition of implementing an interface.

    Now let's consider embedded interfaces. For a case like type O1 interface{ E }, the type set of O1 is the same as the type set of E. The case type O2 interface{ E1; E2 } is more interesting: the type set of O2 is the intersection of the type sets of E1 and E2. To see this, observe that the type set of E1 is the set of all types that implement all the methods of E1, and similarly for E2. What we want for the type set of O2 is the set of all types that implement all the methods of O2. The methods of O2 are all of the methods of E1 combined with all of the methods of E2. The set of types that implement all the methods of both E1 and E2 is the intersection of the type sets of E1 and E2.

    Note that listing a method in an interface type definition in the usual way is, from a type set perspective, indistinguishable from embedding an interface that declares just that method. Although a method by itself is not a type, for our purposes we can say that the type set for a method listed explicitly in an interface type definition is exactly the type set of an interface type with only that method: the set of all types that implement that method. The advantage of doing this is that we can now say that the type set of an interface type is exactly the intersection of the type sets of each element listed in the interface.

    We've now described type sets, and we've explained the meaning of implementing an interface in terms of type sets. None of this changes the language in any way, but it serves as background and motivation for the next steps.

    Proposal

    We propose to replace type lists as defined by the generics proposal with three new, simpler, ideas.

    An interface type that is used as a constraint, or that is embedded in a constraint, is permitted to embed some additional constructs that we will call interface elements. An interface element can be:

    1. Any type, not just an interface type.
    2. A new syntactic construct called an approximation element.
    3. A new syntactic construct called a union element.

    With these new elements we will be able to state simply that a type argument A satisfies a constraint C exactly when A implements the interface type C, or, in terms of type sets, exactly when A is a member of the type set of C.

    First, we propose that an interface type used as a constraint is permitted to embed a non-interface type. For example: type Integer interface{ int }. As discussed in the previous section, the type set of an interface type is the intersection of the type sets of the elements of the interface. The type set of int is simply {int}. This means that the type set of Integer is also {int}. This constraint can be satisfied by any type that is a member of the set {int}. There is exactly one such type: int.

    Of course, that is useless by itself. For constraint satisfaction, we want to be able to say not just int, but "any type whose underlying type is int." To implement this, we propose a new syntactic construct, which may be embedded in an interface type used as a constraint. This is an approximation element, written as ~T. The type set of an approximation ~T is the set of all types whose underlying type is T. An approximation ~T is only valid if the underlying type of T is itself T; this is discussed in more detail below.

    For example: type AnyInt interface{ ~int }. The type set of ~int, and therefore the type set of AnyInt, is the set of all types whose underlying type is int. For example, if MyInt is defined as type MyInt int, then MyInt used as a type argument will satisfy the constraint AnyInt.

    The final step is another new syntactic construct that may be embedded in an interface type used as a constraint: a union element. A union element is written as a sequence of types or approximation elements separated by vertical bars (|). For example: int | float32 or ~int8 | ~int16 | ~int32 | ~int64. The type set of a union element is the union of the type sets of each element in the sequence. The types and elements listed in a union must all be different: no two types may be identical, and no two approximation elements ~T1 and ~T2 may have T1 identical to T2. For example:

    type PredeclaredSignedInteger interface {
    	int | int8 | int16 | int32 | int64
    }
    

    The type set of this union element is the set {int, int8, int16, int32, int64}. Since the union is the only element of PredeclaredSignedInteger, that is also the type set of PredeclaredSignedInteger. This constraint can be satisfied by any of those five types.

    Here is an example using approximation elements:

    type SignedInteger interface {
    	~int | ~int8 | ~int16 | ~int32 | ~int64
    }
    

    The type set of this constraint is the set of all types whose underlying type is one of int, int8, int16, int32, or int64. Any of those types will satisfy this constraint. This is the equivalent of the notation used in the generics proposal

    interface {
    	type int, int8, int16, int32, int64
    }
    

    The use of explicit approximation elements clarifies when we are matching on underlying types, the use of | instead of , emphasizes that this is a union of elements, and the type keyword can be omitted by permitting constraints to embed non-interface elements.

    The purpose of introducing type lists in the generics proposal was to specify the operations available to type parameters in parameterized functions. This is easy to define based on the idea of type sets. Given a type parameter P with a constraint C, a parameterized function is permitted to use an operation with a value of type P if the operation is permitted for every member of the type set of C.

    That is the complete proposal: a conceptual change to use type sets, and three new syntax changes. We will now mention some details and ramifications.

    Approximation elements

    The new ~T syntax will be the first use of ~ as a token in Go.

    Since ~T means the set of all types whose underlying type is T, it will be an error to use ~T with a type T whose underlying type is not itself. Types whose underlying types are themselves are:

    1. Type literals, such as []byte or struct{ f int }.
    2. Predeclared types, such as int or string.

    We do not permit ~P where P is a type parameter.

    The type set of ~T is an infinite set of types.

    The ~ will bind more tightly than |. ~T1 | T2 means (~T1) | (T2), not ~(T1 | T2) (note that ~(T1 | T2) is not syntactically valid)..

    The new syntax is

    InterfaceType = "interface" "{" { ( MethodSpec | InterfaceTypeName | ConstraintElem ) ";" } "}" .
    ConstraintElem = ConstraintTerm { "|" ConstraintTerm } .
    ConstraintTerm = [ "~" ] Type .
    

    Embedding constraints

    A constraint can embed another constraint. Union elements can include constraints.

    // Signed is a constraint whose type set is any signed integer type.
    type Signed interface {
    	~int | ~int8 | ~int16 | ~int32 | ~int64
    }
    
    // Unsigned is a constraint whose type set is any unsigned integer type.
    type Unsigned interface {
    	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
    }
    
    // Float is a constraint whose type set is any floating point type.
    type Float interface {
    	~float32 | ~float64
    }
    
    // Ordered is a constraint whose type set is any ordered type.
    // That is, any type that supports the < operator.
    type Ordered interface {
    	Signed | Unsigned | Float | ~string
    }
    

    Interface types in union constraint elements

    The type set of a union element is the union of the type sets of all elements in the union. For most types T the type set of T is simply T itself. For interface types (and approximation elements), however, this is not the case.

    The type set of an interface type that does not embed a non-interface element is the set of all types that implement the interface, including the interface type itself. Using such an interface type in a union element will add that type set to the union. For example:

    type Stringish interface {
    	string | fmt.Stringer
    }
    

    The type set of Stringish will be the type string and all types that implement fmt.Stringer. Any of those types (including fmt.Stringer itself) will be permitted as a type argument for this constraint. No operations will be permitted for a value of a type parameter that uses Stringish as a constraint (other than operations supported by all types). This is because fmt.Stringer is in the type set of Stringish, and fmt.Stringer, an interface type, does not support any type-specific operations. The operations permitted by Stringish are those operations supported by all the types in the type set, including fmt.Stringer, so in this case there are no operations other than those supported by all types. A parameterized function that uses this constraint will have to use type assertions or reflection in order to use the values. Still, this may be useful in some cases for stronger static type checking. The main point is that it follows directly from the definition of type sets and constraint satisfaction.

    Combining embedded non-interfaces with methods

    A constraint can embed a constraint element and also list methods.

    type StringableSignedInteger interface {
    	~int | ~int8 | ~int16 | ~int32 | ~int64
    	String() string
    }
    

    The rules for type sets define what this means. The type set of the union element is the set of all types whose underlying type is one of the predeclared signed integer types. The type set of String() string is the set of all types that declare that method. The type set of StringableSignedInteger is the intersection of those two type sets. The result is the set of all types whose underlying type is one of the predeclared signed integer types and that declare the method String() string. A function that uses a parameterized type P that uses StringableSignedInteger as a constraint may use the operations permitted for any integer type (+, *, and so forth) on a value of type P. It may also call the String method on a value of type P to get back a string.

    Empty type sets

    It is possible to write a constraint with an empty type set. There is no type argument that will satisfy such a constraint. ~~The compiler should give an error whenever it detects such an unsatisfiable constraint. However, in general a compiler may not be able to detect all such cases.~~ It is not feasible to detect all such cases, though they can't be used with any type argument. It may be appropriate to have vet give an error for cases that it can detect.

    // Unsatisfiable is an unsatisfiable constraint with an empty type set.
    // No predeclared types have any methods.
    // If this used ~int | ~float32 the type set would not be empty.
    type Unsatisfiable interface {
    	int | float32
    	String() string
    }
    

    Method sets of constraint elements

    Much as the type set of an interface type is the intersection of the type sets of the elements of the interface, the method set of an interface type can be defined as the union of the method sets of the elements of the interface. In most cases, an embedded element will have no methods, and as such will not contribute any methods to the interface type. That said, for completeness, we'll note that the method set of ~T is the method set of T. The method set of a union element is the intersection of the method sets of the elements of the union. These rules are implied by the definition of type sets, but they are not needed for understanding the behavior of constraints.

    Possible future step: permitting constraints as ordinary interface types

    We have proposed that constraints can embed some additional elements. With this proposal, any interface type that embeds anything other than an interface type can only be used as a constraint or as an embedded element in another constraint. A natural next step would be to permit using interface types that embed any type, or that embed these new elements, as an ordinary type, not just as a constraint.

    We are not proposing that today. But the rules for type sets and methods set above describe how they would behave. Any type that is an element of the type set could be assigned to such an interface type. A value of such an interface type would permit calling any member of the corresponding method set.

    This would permit a version of what other languages call sum types or union types. It would be a Go interface type to which only specific types could be assigned. Such an interface type could still take the value nil, of course, so it would not be quite the same as a typical sum type.

    In any case, this is something to consider in a future proposal, not this one.

  • proposal: leave

    proposal: leave "if err != nil" alone?

    The Go2 proposal #32437 adds new syntax to the language to make the if err != nil { return ... } boilerplate less cumbersome.

    There are various alternative proposals: #32804 and #32811 as the original one is not universally loved.

    To throw another alternative in the mix: Why not keep it as is?

    I've come to like the explicit nature of the if err != nil construct and as such I don't understand why we need new syntax for this. Is it really that bad?

  • slices: new package to provide generic slice functions

    slices: new package to provide generic slice functions

    Note: Discussion is now at https://github.com/golang/go/discussions/47203.

    This proposal is for use with #43651. We propose defining a new package, slices, that will provide functions that may be used with slices of any type. If this proposal is accepted, the new package will be included with the first release of Go that implements #43651 (we currently expect that that will be Go 1.18).

    This description below is focused on the API, not the implementation. In general the implementation will be straightforward. The description has been updated from the original proposal several times based on the discussion.

    // Package slices defines various functions useful with slices of any type.
    // Unless otherwise specified, these functions all apply to the elements
    // of a slice at index 0 <= i < len(s).
    package slices
    
    import "constraints" // See #45458 
    
    // Equal reports whether two slices are equal: the same length and all
    // elements equal. If the lengths are different, Equal returns false.
    // Otherwise, the elements are compared in index order, and the
    // comparison stops at the first unequal pair.
    // Floating point NaNs are not considered equal.
    func Equal[T comparable](s1, s2 []T) bool
    
    // EqualFunc reports whether two slices are equal using a comparison
    // function on each pair of elements. If the lengths are different,
    // EqualFunc returns false. Otherwise, the elements are compared in
    // index order, and the comparison stops at the first index for which
    // eq returns false.
    func EqualFunc[T1, T2 any](s1 []T1, s2 []T2, eq func(T1, T2) bool) bool
    
    // Compare compares the elements of s1 and s2.
    // The elements are compared sequentially starting at index 0,
    // until one element is not equal to the other. The result of comparing
    // the first non-matching elements is the result of the comparison.
    // If both slices are equal until one of them ends, the shorter slice is
    // considered less than the longer one
    // The result will be 0 if s1==s2, -1 if s1 < s2, and +1 if s1 > s2.
    func Compare[T constraints.Ordered](s1, s2 []T) int
    
    // CompareFunc is like Compare, but uses a comparison function
    // on each pair of elements. The elements are compared in index order,
    // and the comparisons stop after the first time cmp returns non-zero.
    // The result will be the first non-zero result of cmp; if cmp always
    // returns 0 the result is 0 if len(s1) == len(s2), -1 if len(s1) < len(s2),
    // and +1 if len(s1) > len(s2).
    func CompareFunc[T any](s1, s2 []T, cmp func(T, T) int) int
    
    // Index returns the index of the first occurrence of v in s, or -1 if not present.
    func Index[T comparable](s []T, v T) int
    
    // IndexFunc returns the index into s of the first element
    // satisfying f(c), or -1 if none do.
    func IndexFunc[T any](s []T, f func(T) bool) int
    
    // Contains reports whether v is present in s.
    func Contains[T comparable](s []T, v T) bool
    
    // Insert inserts the values v... into s at index i, returning the modified slice.
    // In the returned slice r, r[i] == the first v.  Insert panics if i is out of range.
    // This function is O(len(s) + len(v)).
    func Insert[S constraints.Slice[T], T any](s S, i int, v ...T) S
    
    // Delete removes the elements s[i:j] from s, returning the modified slice.
    // Delete panics if s[i:j] is not a valid slice of s.
    // Delete modifies the contents of the slice s; it does not create a new slice.
    // Delete is O(len(s)-(j-i)), so if many items must be deleted, it is better to
    // make a single call deleting them all together than to delete one at a time.
    func Delete[S constraints.Slice[T], T any](s S, i, j int) S
    
    // Clone returns a copy of the slice.
    // The elements are copied using assignment, so this is a shallow clone.
    func Clone[S constraints.Slice[T], T any](s S) S
    
    // Compact replaces consecutive runs of equal elements with a single copy.
    // This is like the uniq command found on Unix.
    // Compact modifies the contents of the slice s; it does not create a new slice.
    func Compact[S constraints.Slice[T], T comparable](s S) S
    
    // CompactFunc is like Compact, but uses a comparison function.
    func CompactFunc[S constraints.Slice[T], T any](s S, cmp func(T, T) bool) S
    
    // Grow grows the slice's capacity, if necessary, to guarantee space for
    // another n elements. After Grow(n), at least n elements can be appended
    // to the slice without another allocation. If n is negative or too large to
    // allocate the memory, Grow will panic.
    func Grow[S constraints.Slice[T], T any](s S, n int) S
    
    // Clip removes unused capacity from the slice, returning s[:len(s):len(s)].
    func Clip[S constraints.Slice[T], T any](s S) S
    
  • proposal: cmd/go: make major versions optional in import paths

    proposal: cmd/go: make major versions optional in import paths

    Semantic Import Versioning (SIV) is a novel idea for supporting multiple versions of a package within the same program. To my knowledge and experience, it's the first example of a strategy for supporting multiple versions of a project / dependency in the same application. More importantly though, its clever introductory design allowed it to offer multi-versioned packages in a Go program while maintaining Go's compatibility guarantee.

    Multi-versioned packages in a single program can be quite powerful -- for instance, imagine a Web service where you'd like to maintain backwards compatible support for your consumers, you can simply use an older import path from the same origin repository and versioning control, and quite elegantly continue to support those older API versions.

    Although SIV may be an elegant solution in the scenario described above, it also adds unnecessary complexity, cost, code noise, discoverability and ergonomics for the majority of packages (publicly and privately) which may not ever have a mutli-version requirement (I'd argue most packages, and simply we can look to other ecosystems to see this is true). I am sure the Go team has heard a lot of feedback on the friction of SIV. https://twitter.com/peterbourgon/status/1236657048714182657?s=21 and https://peter.bourgon.org/blog/2020/09/14/siv-is-unsound.html offers some excellent points as well.

    Clearly there is a case for SIV as an elegant solution for supporting multiple versions of a package in a single application, and there is also a strong case to make SIV optional.

    It's clear to me there is a design trade-off at hand, and there is no single correct answer. As I consider the 80/20 rule in making an architectural decision between two trade-offs of capability and usability, I prefer to go with the 80% case so long as it doesn't forego the 20% ability. Which design is the best to optimize for if we can still support both? In the case with Go today, its not possible to opt-out of SIV, or opt-into SIV -- I believe both approaches can yield a happy solution. If we were starting from the beginning, I'd suggest to have SIV be opt-in, but maybe at this point its better for it to be an opt-out design to maintain backwards compatibility with history.


    I'd like to propose a path to make SIV opt-out at the level of an application developer consuming a package, while being backwards compatible with current packages and tools.

    I'd like to use https://github.com/go-chi/chi as an example for this proposal which adopted semver ahead of Go modules and SIV, and is built for developer simplicity and ergonomics intended for pro Go developers, but also making it familiar and accessible for developers who are new to Go -- these are my design goals for chi as an author and maintainer as started back in 2017. My present goal is to release Chi v5 without a SIV requirement and the only way I can do so is with the proposal below:


    Proposal, by example:

    github.com/go-chi/chi/go.mod:

    module github.com/go-chi/chi/v5
    
    go 1.16
    

    then, git tag chi as v5.0.0 to make the release.

    Application developers may consume the package via go get github.com/go-chi/chi@latest or with @v5 or @v5.0.0 and the expected import path will be "github.com/go-chi/chi", however "github.com/go-chi/chi/v5" import path would also be valid and usable.

    In the above case, we're specifying the go.mod as expected with current behaviour with SIV from a library perspective. However, from the application perspective when fetching or consuming the library, I may opt-out of the "/v5" suffix in the import path and only adopt it in the scenario when I'd like to support "/v5" and "/v4" (or some other prior version), where I require the handling of multiple versions simultaneously in my program.

    I believe the implementation of the above to be backwards compatible as developers would continue to use "github.com/go-chi/chi/v5" with older version of Go as SIV is implied, but optionally developers could make their choice of multiple-version support for the package by handling the import paths themselves and import "github.com/go-chi/chi" to utilize v5.x.x as specified by go.mod.

    I believe changes to the Go toolchain for such support would be minimal and would be isolated to the components which build module lists.

    Thank you for reading my proposal, and its consideration.

  • proposal: all: add plan9/arm64 port

    proposal: all: add plan9/arm64 port

    Hi!

    It would be great to support plan9/arm64. With plan9front it could be used on the MNT Reform and on the Raspberry Pi. The implementation would be similar to plan9/arm.

    Also there's a first draft which can already be used. Most tests pass but more work is needed.

    Greetings, Philip

  • proposal: sync: add golang.org/x/sync/errgroup

    proposal: sync: add golang.org/x/sync/errgroup

    As briefly discussed in https://github.com/golang/go/issues/56102#issuecomment-1317765390, I propose to promote errgroup.Group to the sync package. The proposed API set is listed below.

    Rationale

    Compared to sync.WaitGroup, errgroup.Group do not require cognitive load to manage Add() and Done() and can easily manage the number of concurrent tasks using SetLimit. For example,

    g := sync.WaitGroup{}
    sem := make(chan struct{}, 5)
    for i := 0; i < n; i++ {
    	sem <- struct{}{}
    	g.Add(1)
    	go func() {
    		defer func() {
    			g.Done()
    			<-sem
    		}()
    
    		// ...
    	}()
    }
    g.Wait()
    

    vs.

    g := errgroup.Group{}
    g.SetLimit(5)
    for i := 0; i < n; i++ {
    	g.Go(func() {
    		// ...
    	})
    }
    g.Wait()
    

    Tu et al. [1] also reported that WaitGroup is often misused and causes concurrency bugs. For instance, an example taken from Figure 9:

    func (p *peer) send() {
    	p.mu.Lock()
    	defer p.mu.Unlock()
    	switch p.status {
    		case idle:
    +			p.wg.Add(1)
    			go func() {
    -				p.wg.Add(1)
    				...
    				p.wg.Done()
    			}()
    		case stopped:
    	}
    }
    
    func (p * peer) stop() {
    	p.mu.Lock()
    	p.status = stopped
    	p.mu.Unlock()
    	p.wg.Wait()
    }
    

    [1] Tu, Tengfei, et al. "Understanding real-world concurrency bugs in go." Proceedings of the Twenty-Fourth International Conference on Architectural Support for Programming Languages and Operating Systems. 2019. https://doi.org/10.1145/3297858.3304069

    Existing Usage

    A search over GitHub, code that uses errgroup.Group includes 16.1k files and pkg.go.dev shows there are 10,456 imports.

    APIs

    package sync
    
    // An ErrGroup is a collection of goroutines working on subtasks that are part of
    // the same overall task.
    //
    // A zero ErrGroup is valid, has no limit on the number of active goroutines,
    // and does not cancel on error.
    type ErrGroup struct
    
    // SetLimit limits the number of active goroutines in this group to at most n.
    // A negative value indicates no limit.
    //
    // Any subsequent call to the Go method will block until it can add an active
    // goroutine without exceeding the configured limit.
    //
    // The limit must not be modified while any goroutines in the group are active.
    func (g *ErrGroup) SetLimit(n int)
    
    // Go calls the given function in a new goroutine.
    // It blocks until the new goroutine can be added without the number of
    // active goroutines in the group exceeding the configured limit.
    //
    // The first call to return a non-nil error cancels the group's context, if the
    // group was created by calling WithContext. The error will be returned by Wait.
    func (g *ErrGroup) Go(f func() error)
    
    // TryGo calls the given function in a new goroutine only if the number of
    // active goroutines in the group is currently below the configured limit.
    //
    // The return value reports whether the goroutine was started.
    func (g *ErrGroup) TryGo(f func() error) bool
    
    // Wait blocks until all function calls from the Go method have returned, then
    // returns the first non-nil error (if any) from them.
    func (g *ErrGroup) Wait() error
    
    // NewErrGroupWithContext returns a new ErrGroup and an associated Context derived from ctx.
    //
    // The derived Context is canceled the first time a function passed to Go
    // returns a non-nil error or the first time Wait returns, whichever occurs
    // first.
    func NewErrGroupWithContext(ctx context.Context) (*ErrGroup, context.Context)
    

    Update: WithContext is renamed to NewErrGroupWithContext.

  • x/build/devapp/owners: document role of primaries and secondaries

    x/build/devapp/owners: document role of primaries and secondaries

    Go Code Owners page https://dev.golang.org/owners lists primaries and secondaries by project. The page should explain what this information means -- what do code owners do?

    I think Gerrit https://go-review.googlesource.com/ automatically adds primaries as reviewers.

  • x/crypto/ssh: write errors should be returned immediately

    x/crypto/ssh: write errors should be returned immediately

    Apologies if this is a duplicate or not actually a bug.

    What version of Go are you using (go version)?

    $ go version
    go version go1.18.4 linux/amd64
    

    x/crypto master

    Does this issue reproduce with the latest release?

    Yes, this behavior hasn't changed since it was introduced in https://github.com/golang/crypto/commit/2e74c773682f59dc50a56475f7918dd8fa6dcaf8 .

    What did you do?

    Write to a channel of an SSH connection that's interrupted, e.g. by receiving a TCP RST.

    What did you expect to see?

    A write error is reported as soon as writing to the underlying net.Conn fails.

    What did you see instead?

    The error is reported only on subsequent writes. This is not a dire problem, but seems odd/unnecessary.

    In particular, handshakeTransport.writePacket sets t.writeError but returns nil. This seems to have been introduced in the aforelinked https://github.com/golang/crypto/commit/2e74c773682f59dc50a56475f7918dd8fa6dcaf8 .

    Is there a missing return err here? If so, I can submit a CL.

  • cmd/go: document that go mod vendor ignores directories that do not contain Go files

    cmd/go: document that go mod vendor ignores directories that do not contain Go files

    What version of Go are you using (go version)?

    $ go version
    go1.19.4
    

    Does this issue reproduce with the latest release?

    yes

    What operating system and processor architecture are you using (go env)?

    go env Output
    $ go env
    GO111MODULE=""
    GOARCH="amd64"
    GOBIN=""
    GOCACHE="/home/user/.cache/go-build"
    GOENV="/home/user/.config/go/env"
    GOEXE=""
    GOEXPERIMENT=""
    GOFLAGS=""
    GOHOSTARCH="amd64"
    GOHOSTOS="linux"
    GOINSECURE=""
    GOMODCACHE="/home/user/go/pkg/mod"
    GONOPROXY=""
    GONOSUMDB=""
    GOOS="linux"
    GOPATH="/home/colin/go"
    GOPRIVATE=""
    GOPROXY="direct"
    GOROOT="/nix/store/a7875alzpnr46z6mv4ssymfdwmvr6xbq-go-1.19.4/share/go"
    GOSUMDB="off"
    GOTMPDIR=""
    GOTOOLDIR="/nix/store/a7875alzpnr46z6mv4ssymfdwmvr6xbq-go-1.19.4/share/go/pkg/tool/linux_amd64"
    GOVCS=""
    GOVERSION="go1.19.4"
    GCCGO="gccgo"
    GOAMD64="v1"
    AR="ar"
    CC="gcc"
    CXX="g++"
    CGO_ENABLED="1"
    GOMOD="/dev/null"
    GOWORK=""
    CGO_CFLAGS="-g -O2"
    CGO_CPPFLAGS=""
    CGO_CXXFLAGS="-g -O2"
    CGO_FFLAGS="-g -O2"
    CGO_LDFLAGS="-g -O2"
    PKG_CONFIG="pkg-config"
    GOGCCFLAGS="-fPIC -m64 -pthread -Wl,--no-gc-sections -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build3977569072=/tmp/go-build -gno-record-gcc-switches"
    

    What did you do?

    [user@localhost:~]$ git clone https://github.com/ava-labs/avalanchego
    [user@localhost:~]$ cd avalanchego
    [user@localhost:avalanchego]$ go build -o /dev/null ./main
    [user@localhost:avalanchego]$ go mod vendor
    

    What did you expect to see?

    [user@localhost:avalanchego]$ go build -o /dev/null ./main
    

    What did you see instead?

    [user@localhost:avalanchego]$ go build -o /dev/null ./main
    # github.com/supranational/blst/bindings/go
    vendor/github.com/supranational/blst/bindings/go/blst.go:16:11: fatal error: blst.h: No such file or directory
       16 | // #include "blst.h"
          |           ^~~~~~~~
    compilation terminated.
    # github.com/zondax/hid
    vendor/github.com/zondax/hid/hid_enabled.go:23:18: fatal error: os/threads_posix.c: No such file or directory
       23 |         #include "os/threads_posix.c"
          |                  ^~~~~~~~~~~~~~~~~~~~
    compilation terminated.
    
  • x/pkgsite: packages with an excluded prefix show up in search

    x/pkgsite: packages with an excluded prefix show up in search

    Follow up from #57510

    What is the URL of the page with the issue?

    https://pkg.go.dev/search?q=pixelyte

    Screenshot

    Screenshot 2022-12-30 at 11 26 56 AM

    What did you do?

    Searched for the name of a package that has been excluded from the pkgsite results from the main pkg.go.dev page.

    What did you expect to see?

    No results matching codeberg.org/pixelyte

    What did you see instead?

    The pages for the documentation are correctly not available, but the excluded packages still appear in the results.

    Interestingly, if I search from the results page, there are correctly no results (https://pkg.go.dev/search?q=pixelyte&m=package)

    Screenshot 2022-12-30 at 11 30 29 AM
Goal is a toolkit for high productivity web development in Go language in the spirit of Revel Framework that is built around the concept of code generation.

Goal Goal is a set of tools for high productivity web development in Go language. Goal, being mostly inspired by Revel Framework and its discussions,

Sep 27, 2021
T# Programming Language. Something like Porth, Forth but written in Go. Stack-oriented programming language.

The T# Programming Language WARNING! THIS LANGUAGE IS A WORK IN PROGRESS! ANYTHING CAN CHANGE AT ANY MOMENT WITHOUT ANY NOTICE! Something like Forth a

Jun 29, 2022
Yayx programming language is begginer friendly programming language.
Yayx programming language is begginer friendly programming language.

Yayx Yayx programming language is begginer friendly programming language. What have yayx: Easy syntax Dynamic types Can be compiled to outhers program

Dec 27, 2021
Yayx programming language is begginer friendly programming language.

Yayx Yayx programming language is begginer friendly programming language. What have yayx: Easy syntax Dynamic types Can be compiled to outhers program

May 20, 2022
Advent of Code is an Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

Advent of Code 2021 Advent of Code is an Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved

Dec 2, 2021
Jan 4, 2022
A repository for showcasing my knowledge of the Google Go (2009) programming language, and continuing to learn the language.

Learning Google Golang (programming language) Not to be confused with the Go! programming language by Francis McCabe I don't know very much about the

Nov 6, 2022
A repository for showcasing my knowledge of the Go! (2003) programming language, and continuing to learn the language.
A repository for showcasing my knowledge of the Go! (2003) programming language, and continuing to learn the language.

Learning Go! (programming language) Not to be confused with Google Golang (2009) I don't know too much about the Go! programming language, but I know

Oct 22, 2022
AWS SDK for the Go programming language.

AWS SDK for Go aws-sdk-go is the official AWS SDK for the Go programming language. Checkout our release notes for information about the latest bug fix

Jan 1, 2023
go.fifo provides a simple fifo thread-safe queue for the Go programming language

go.fifo Description go.fifo provides a simple FIFO thread-safe queue. *fifo.Queue supports pushing an item at the end with Add(), and popping an item

Aug 29, 2022
Dynamic object-oriented programming support for the Go language

Goop Description The Goop (Go Object-Oriented Programming) package provides support for dynamic object-oriented programming constructs in Go, much lik

Oct 13, 2022
Eclipse IDE for the Go programming language:
Eclipse IDE for the Go programming language:

Project website: http://goclipse.github.io/ As of 2017, Goclipse is no longer actively maintained, see this blog post for more information. If you are

Dec 20, 2022
Gentee - script programming language for automation. It uses VM and compiler written in Go (Golang).

Gentee script programming language Gentee is a free open source script programming language. The Gentee programming language is designed to create scr

Dec 15, 2022
PHP bindings for the Go programming language (Golang)

PHP bindings for Go This package implements support for executing PHP scripts, exporting Go variables for use in PHP contexts, attaching Go method rec

Jan 1, 2023
Vulkan API bindings for Go programming language
Vulkan API bindings for Go programming language

Golang Bindings for Vulkan API Package vulkan provides Go bindings for Vulkan — a low-overhead, cross-platform 3D graphics and compute API. Updated Oc

Jan 3, 2023
A package to build progressive web apps with Go programming language and WebAssembly.
A package to build progressive web apps with Go programming language and WebAssembly.

go-app is a package to build progressive web apps (PWA) with Go programming language and WebAssembly. It uses a declarative syntax that allows creatin

Dec 28, 2022
A Windows GUI toolkit for the Go Programming Language
A Windows GUI toolkit for the Go Programming Language

About Walk Walk is a "Windows Application Library Kit" for the Go Programming Language. Its primarily useful for Desktop GUI development, but there is

Dec 30, 2022
beego is an open-source, high-performance web framework for the Go programming language.
beego is an open-source, high-performance web framework for the Go programming language.

Beego Beego is used for rapid development of enterprise application in Go, including RESTful APIs, web apps and backend services. It is inspired by To

Jan 1, 2023
BGP implemented in the Go Programming Language

GoBGP: BGP implementation in Go GoBGP is an open source BGP implementation designed from scratch for modern environment and implemented in a modern pr

Dec 31, 2022
A simple wrapper around libpcap for the Go programming language

PCAP This is a simple wrapper around libpcap for Go. Originally written by Andreas Krennmair [email protected] and only minorly touched up by Mark Smith

Dec 5, 2022