Table of Contents
Problem content
Solution
Home Backend Development Golang Generics: Constraints and structures embedded in interfaces

Generics: Constraints and structures embedded in interfaces

Feb 08, 2024 pm 11:21 PM
overflow

Generics: Constraints and structures embedded in interfaces

php editor Xiaoxin brings you an introduction to generics. Generics are constraints and structures embedded in interfaces that allow us to be more flexible and efficient when writing code. By using generics, we can find and resolve type errors at compile time, improving code readability and maintainability. Generics can also help us design more general data structures and algorithms, improving code reusability. In this article, we will delve into the concepts, usage, and practical applications of generics to help you better understand and apply generic programming.

Problem content

The following code cannot be compiled and reports./main.go:35:7: test does not meet constraint (test missing in main.structwithname)

package main

import "fmt"

type Test struct {
    Name string
}

func (t Test) String() string {
    return fmt.Sprintf("Name: %v", t.Name)
}

type StructWithName struct {
    Name string
}

type Constraint interface {
    StructWithName
    // ~struct {
    //  Name string
    // }
    String() string
}

func Print[T Constraint](x T) {
    //s := T{}
    fmt.Printf("Hello %v", x)
}

func main() {
    t := Test{
        Name: "Test",
    }

    Print(t)
}
Copy after login

However, if I comment out the structwithname and uncomment the ~struct block, then it compiles fine. I can't understand the semantic difference between the two.

What I'm trying to do is have a generic method that can handle a struct in a generic way; i.e. x := s{} and then pass it to an external library. In this case it's for the terraform provider, the code in the resources is very similar, I'm a bit bothered by the amount of duplication I see in the existing providers; in my case the resources are very similar, some are in between the default structures There are only one or two fields on it). I'd like to be able to write a set of generic methods that do all similar things, and only have the specificities elsewhere (duh!).

I'm still in the early stages of my go journey and I can't understand the compiler errors.

Solution

If I understand correctly, what you really want is not possible. Go generics do not support accessing a subset of structure fields.

As far as the errors involved...

The name of a type specifies the identity of the type, and two types with different names (not aliases to each other) are always different, so test and structwithname are two different type. The only thing they have in common is their underlying type.

type constraint interface { structwithname } The interface is a type set that contains only one type, that is, structwithname, and since test is not of this type set member, which means it is not possible to use the test type to satisfy the constraint.

type struct { name string } is an unnamed type. The underlying type of any unnamed type is the type itself, that is, the underlying type of struct { name string } is struct { name string }.

The tilde in front of the type in the constraint, that is, ~t, means any type, whose underlying type is the same as t. Or, more accurately,

The type set of an item of the form

~t is the set of all types whose base type is t.

So when you do this

type Constraint interface { ~struct { Name string } }
Copy after login

Then the constrained type set will contain any type that has struct { name string } as its base type.

The above is the detailed content of Generics: Constraints and structures embedded in interfaces. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The price of Bitcoin since its birth 2009-2025 The most complete summary of BTC historical prices The price of Bitcoin since its birth 2009-2025 The most complete summary of BTC historical prices Jan 15, 2025 pm 08:11 PM

Since its inception in 2009, Bitcoin has become a leader in the cryptocurrency world and its price has experienced huge fluctuations. To provide a comprehensive historical overview, this article compiles Bitcoin price data from 2009 to 2025, covering major market events, changes in market sentiment, and important factors influencing price movements.

What to do if the time is gone in the lower right corner of Windows 11_What to do if the time is gone in the lower right corner of Windows 11 What to do if the time is gone in the lower right corner of Windows 11_What to do if the time is gone in the lower right corner of Windows 11 May 06, 2024 pm 01:20 PM

1. First, right-click on the blank space of the taskbar at the bottom of Windows 11 and select [Taskbar Settings]. 2. Find [taskbarcorneroverflow] on the right in the taskbar settings. 3. Then find [clock] or [Clock] above it and select to turn it on. Method 2: 1. Press the keyboard shortcut [win+r] to call up run, enter [regedit] and press Enter to confirm. 2. Open the registry editor, find [HKEY_CURRENT_USERControlPanel] in it, and delete it. 3. After deletion, restart the computer and you will be prompted for configuration. When you return to the system, the time will be displayed.

How to use other people's code in python How to use other people's code in python May 05, 2024 pm 07:54 PM

How do I use other people's Python code? Find code repositories: Find the code you need on platforms like PyPI and GitHub. Installation code: Use pip or clone the GitHub repository to install. Import modules: Use the import statement in your script to import installed modules. Working with code: Access functions and classes in modules. (Optional) Adapt the code: Modify the code as needed to fit your project.

What should I do if the time on my win11 computer is always wrong? How to adjust the wrong time on Windows 11 computer What should I do if the time on my win11 computer is always wrong? How to adjust the wrong time on Windows 11 computer May 03, 2024 pm 09:20 PM

What should I do if the time on my win11 computer is always wrong? We all set the time or calendar when using win11 system, but many users are asking that the computer time is always wrong, so what is going on? Users can directly click on the taskbar below, and then find taskbarcorneroverflow to set it up. Let this site introduce to users in detail how to adjust the time error on Win11 computers. How to adjust the computer time error in Windows 11. Method 1: 1. We first right-click on the blank space of the taskbar below and select Taskbar Settings. Method 2: 1. Press the keyboard shortcut win+r to call up run, enter regedit and press Enter to confirm.

Common exception types and their repair measures in Java function development Common exception types and their repair measures in Java function development May 03, 2024 pm 02:09 PM

Common exception types and their repair measures in Java function development During the development of Java functions, various exceptions may be encountered, which affect the correct execution of the function. The following are common exception types and their repair measures: 1. NullPointerException Description: Thrown when accessing an object that has not been initialized. Fix: Make sure you check the object for non-null before using it. Sample code: try{Stringname=null;System.out.println(name.length());}catch(NullPointerExceptione){

Doesn't anyone take care of Douyin's random accounts? Can I appeal a second time? Doesn't anyone take care of Douyin's random accounts? Can I appeal a second time? May 03, 2024 am 09:37 AM

As a world-renowned short video platform, Douyin has a huge user base and content creators. However, as the platform rules are constantly updated and improved, some users may encounter account bans. This has raised public questions about the transparency and fairness of platform management. This article will discuss the issue of Douyin account bans and whether users have ways to appeal after their accounts are banned. There may be many reasons for being banned on the Douyin platform, including but not limited to illegal content, violation of platform regulations, infringement of other people's rights, etc. In order to maintain the order of the platform and the interests of users, Douyin has set up a series of rules and review mechanisms. When some users violate the rules, their accounts may be banned. However, some users may question or be dissatisfied with the reasons for the ban

What is the relationship between recursive calls and exception handling in Java functions? What is the relationship between recursive calls and exception handling in Java functions? May 03, 2024 pm 06:12 PM

Exception handling in recursive calls: Limiting recursion depth: Preventing stack overflow. Use exception handling: Use try-catch statements to handle exceptions. Tail recursion optimization: avoid stack overflow.

What are the debugging techniques for recursive calls in Java functions? What are the debugging techniques for recursive calls in Java functions? May 05, 2024 am 10:48 AM

The following techniques are available for debugging recursive functions: Check the stack traceSet debug pointsCheck if the base case is implemented correctlyCount the number of recursive callsVisualize the recursive stack

See all articles