Home > Backend Development > Golang > How Can You Store Both String and Int Values in a Go Struct?

How Can You Store Both String and Int Values in a Go Struct?

Patricia Arquette
Release: 2024-12-03 10:58:09
Original
995 people have browsed it

How Can You Store Both String and Int Values in a Go Struct?

Storing Both String and Int Values in a Go Struct

In Go, it's not possible to store both string and int values directly in a single struct field. This is due to the language's strong type system, which requires variables to have specific, well-defined types.

Possible Solutions

To work around this limitation, you have a few options:

  1. Convert the Input Dynamically: You can convert the int input to a string when needed and convert it back to int when processing.
  2. Define Multiple Structs: You can define separate structs for different input types, such as testCaseString and testCaseInt.
  3. Interface Implementation: As of Go 1.18, you can use interfaces as a workaround. While Go does not have native sum types, it does allow you to define interfaces that multiple types can implement.

Interface Implementation in Go 1.18 and Beyond

Using an interface, you can create a type that can hold both string and int values. Here's an example:

type Input interface {
    IsValid() bool
    Value() interface{}
}

type TestCaseBool struct {
    input   bool
    isValid bool
}

func (tc TestCaseBool) IsValid() bool {
    return tc.isValid
}

func (tc TestCaseBool) Value() interface{} {
    return tc.input
}
Copy after login

You can now use the TestCaseBool struct to hold either a boolean value or an empty interface.

Note: This solution requires Go 1.18 or higher to work.

The above is the detailed content of How Can You Store Both String and Int Values in a Go Struct?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template