DEV Community

Weerasak Chongnguluam
Weerasak Chongnguluam

Posted on • Edited on

2

ทำไมเราถึงเห็นข้อมูลแบบ []byte หลายที่ใน standard package ของ Go

#go

เราจะมักจะเห็นข้อมูลแบบ []byte อยู่หลายที่ใน standard package ของ Go ไม่ว่าจะเป็น io.Reader, io.Writer interface หรือจะใน package net/http และใน encoding/json

slice ของ byte เนี่ยมันก็แค่ลำดับของตัวเลขที่มีในช่วง 0-255 หลายๆตัว ซึ่งถ้าเราพิพม์ออกมาดูเนี่ย จะไม่รู้เลยว่ามันหมายถึงอะไร ที่เป็นแบบนี้เพราะมันคือ raw data ยังไงล่ะ

raw data จุดที่ถูกใช้ก็คือ จุดที่เราใช้ส่งข้อมูลโดยที่ไม่สนใจรูปแบบของข้อมูล ไม่ว่าจะเป็นเรื่อง IO (Input/Output) ที่ต้องส่งต่อให้อุปกรณ์ภายนอกหรือคุยกับ OS (Operating System) หรือคุยกับ Network พวก package net/http ที่ต้องส่งข้อมูลผ่าน protocol HTTP และข้อมูลที่ต้องผ่านการ encode/decode ต่างๆพวก package ในกลุ่ม encoding ไม่ว่าจะเป็น encoding/json, encoding/xml

พวกนี้ข้อมูลต้องถูกแปลงไป แปลงมา ระหว่าง format ต้นทาง กับ raw data ([]byte) เพื่อให้ปลายทางไปแปลงกลับอีกรอบได้

แต่อย่างไรก็ตามเราเองอาจจะไม่ได้จัดการ []byte เองโดยตรงเท่าไหร่เพราะมี package ในการแปลงข้อมูลให้เราอยู่แล้ว อย่างมากก็อาจจะแปลงจาก string ไปเป็น []byte แล้วแปลงกลับเป็น string อีกที ยกเว้นก็แต่เราต้องเขียน package เพื่อจัดการอะไรในระดับ protocol หรือ I/O ในระดับล่างๆ หรือจัดการแปลง raw data ไปมาเป็น format ที่ยังไม่เคยมีใครทำมาก่อน

Buy Me A Coffee

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay