Created
December 11, 2021 00:39
-
-
Save ivanauliaa/b581ef529d99b919bcb46ce57852b910 to your computer and use it in GitHub Desktop.
Golang special user defined data types with additional behavior
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package special | |
import ( | |
"fmt" | |
"strconv" | |
) | |
// Special Type: int as Integer | |
type Integer int | |
// Format an Integer data to string | |
func (x Integer) ToString() string { | |
return strconv.Itoa(int(x)) | |
} | |
// Special Type: float64 as Float | |
type Float float64 | |
// Format a Float data to string with 6 digit precision | |
func (x Float) ToString() string { | |
return fmt.Sprintf("%f", x) | |
} | |
// Special Type: string as String | |
type String string | |
// Format a String data into lowercase letter | |
func (str String) ToLowercase() string { | |
strByte := []byte{} | |
for i := 0; i < len(str); i++ { | |
if str[i] >= 65 && str[i] <= 90 { | |
strByte = append(strByte, str[i]+32) | |
} else { | |
strByte = append(strByte, str[i]) | |
} | |
} | |
return string(strByte) | |
} | |
// Format a String data into uppercase letter | |
func (str String) ToUppercase() string { | |
strByte := []byte{} | |
for i := 0; i < len(str); i++ { | |
if str[i] >= 97 && str[i] <= 122 { | |
strByte = append(strByte, str[i]-32) | |
} else { | |
strByte = append(strByte, str[i]) | |
} | |
} | |
return string(strByte) | |
} | |
// Reverse String data's character set | |
func (str String) Reverse() string { | |
strByte := []byte{} | |
for i := len(str) - 1; i >= 0; i-- { | |
strByte = append(strByte, str[i]) | |
} | |
return string(strByte) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment