Convert a string to the type of a string value

WBOY
Release: 2024-02-10 23:40:08
forward
468 people have browsed it

Convert a string to the type of a string value

php editor Baicao is here to introduce how to convert strings into different types of values. In programming, we often need to convert strings to other types, such as integers, floating point numbers, Boolean values, etc. PHP provides a series of built-in functions and methods to implement this conversion process, allowing us to easily convert strings into the types we need. The following will introduce in detail several commonly used string conversion methods to help everyone better master this technique.

Question content

I want to dynamically create a type instance based on a string value. For example, given the following:

type MyType struct {}

var input = "MyType"

var result = GetType(input)
Copy after login

I want reflect.TypeOf(result) == MyType to be true.

The best I can think of is to use map[string]MyInterface{} as a lookup for each type that satisfies MyInterface, but that's not the dynamic I want, Because it requires me to update the table with each new type I create. GetType(string) Is there any logic inside that I can use to do this more dynamically?

Solution

In Go, types are statically defined at compile time, you cannot dynamically create or change types at runtime based on string values. Therefore, what you ask for is not directly achieved using the built-in type system.

The above is the detailed content of Convert a string to the type of a string value. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template