GO 학습 : - 파일 처리, 오류 처리

Mary-Kate Olsen
풀어 주다: 2024-10-15 12:06:41
원래의
964명이 탐색했습니다.

Learning GO : - File Handling, Error Handling

Hey! I am Currently learning Go Lang, and I am taking some basic Notes on my Notion and though I'd also just publish them here. They are not well thought out or well written but it's just me taking notes from time to time for my reference.

I am taking the Udemy Course by Maximilian Schwarzmüller,


Notes

Writing in Files

  • the os package provides a function called WriteFile that takes in the name of the package, the data to be stored in the file and file mode, which will be the file modifying permissions.
func writeBalanceFiles(balance float64) {
    balanceText := fmt.Sprint(balance)
    os.WriteFile("balance.txt", []byte(balanceText), 0644)
}
로그인 후 복사

Reading from a file

  • sometimes when we are getting 2 return values from a function, we can then use a special variable name _ that means we want get the value but we dont want to use it.
data, _ := os.ReadFile("balance.txt")
로그인 후 복사
  • here the data will come with a byte type, so to handle that, we can only convert that data into a string
  • we need the data string in float number, so for that we can use the strconv package, that gives us different methods to handle string operations
  • we can use ParseFloat method, which will convert the string into floating number, with that we will need to provide the string value and bitSize which will be 32 or 64
func readFile() float64 {
    data, _ := os.ReadFile("balance.txt")
    balanceText := string(data)
    balance, _ := strconv.ParseFloat(balanceText, 64)
    return balance
}
로그인 후 복사
  • byte values cannot be directly converted into any type other then string and string value directly cannot be converted into any other type, that will require the use of strconv package

Error handling

  • In GO, there is a special type as error that can be used to give out custom errors which comes from the built in errors package
  • In GO, we can use nil to check the null value
  • almost all packages provide an error as return value with a main value, we use the error to to check if there is nil value
  • So, if the error is not nil that means there is an error and in that case we can give out some error response
    if err != nil {
        return 1000, errors.New("failed to find balance file")
    }

로그인 후 복사
    var accountBalance, err = readFile()

    if err != nil {
        fmt.Println("ERROR")
        fmt.Println(err)
        fmt.Println("===============")
    }
로그인 후 복사

Panic!

  • there is an in built method called panic() that will stop the program execution and give out special error
    if err != nil {
        fmt.Println("ERROR")
        fmt.Println(err)
        fmt.Println("===============")
        panic("Can't Continue Sorry!")
    } 
로그인 후 복사

위 내용은 GO 학습 : - 파일 처리, 오류 처리의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!