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.
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)
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?
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!