“nil” คืออะไร ใน Programing

จากคนที่เขียน Node ย้ายมา Go แล้วเอะใจอะไรบางอย่าง ทำให้เกิดข้อสงสัยว่ามันคืออะไรกันนะ ไอ้เจ้า “nil” เนี่ย ถ้าอยากรู้ ลองไปดูกัน

Ton Piromplad
Feb 5, 2021

--

รากศัพท์ของคำว่า nil มาจาก ภาษาละติน คำว่า nihil, nihilum ซึ่งแปลว่า “nothing” หรือ “ว่างเปล่า, ไม่มีอะไร” แต่ในบางภาษาก็อาจจะเจอเป็น “null” ได้เหมือนกัน ซึ่งก็ให้ความหมายเดียวกับ nil เช่นกัน แล้วในทาง programing มันคืออะไรล่ะ

ในทาง programing นั้น จากที่ได้หาข้อมูลก็พบว่า จะหมายความตามนั้นเลย ซึ่งจะใช้นิยาม ให้กับตัวแปรแต่ละประเภท ที่สามารถเป็นค่าว่างเปล่าได้ หรือที่เรียกว่า “nullable types” โดยการให้ค่าว่างเปล่า นั้น ไม่ได้แปลว่า มีค่าเป็น 0 หรือ ข้อความว่างๆ

ซึ่ง ประเภทของตัวแปรที่สามารถเป็นค่าว่างได้ มีดังนี้

  • map list (object)
  • set (array)
  • pointer

แต่ nil นั้นต่างกับ zero value นะ และ zero value ในทาง programing ไม่ได้หมายความว่ามีค่าเป็น 0 เสมอไป
ในส่วนของ ภาษา golang หรือ ภาษาต่างๆที่เป็น strongly-typed programming language เช่น C, GO, JAVA จะให้ความหมายว่า เป็นค่าเริ่มต้นของตัวแปร แต่ละประเภทนั่นเอง

เช่นใน golang จะเป็นดังต่อไปนี้

  • Integer -> 0
  • Floating point -> 0.0
  • Boolean -> false
  • String -> “”
  • Pointer -> nil
  • Interface -> nil
  • Slice -> nil
  • Map -> nil
  • Channel -> nil
  • Function -> nil

ก็ประมาณนี้แหละครับ กับสิ่งที่เรียกว่า NIL

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Ton Piromplad
Ton Piromplad

Written by Ton Piromplad

Programmer ที่ชอบดูหนัง เล่นเกมมากกว่าเขียนโค้ด

No responses yet

Write a response